Use a list of values to select rows from a pandas dataframe

To select rows from a Pandas DataFrame using a list of values, you can use the isin() method along with boolean indexing.

First let's create a data frame with values.

import pandas as pd import numpy as np df = pd.DataFrame() df['Name'] = ['John', 'Doe', 'Bill','Jim','Harry','Ben'] df['TotalMarks'] = [82, 38, 63,22,55,40] df['Grade'] = ['A', 'E', 'B','E','C','D'] df['Promoted'] = [True, False,True,False,True,True] df
Name TotalMarks Grade Promoted 0 John 82 A True 1 Doe 38 E False 2 Bill 63 B True 3 Jim 22 E False 4 Harry 55 C True 5 Ben 40 D True

Create a list of values for select rows:

lst = ['Doe', 'Bill', 'Ben']

The isin() method is a convenient way to select rows from a Pandas DataFrame based on a list of values. It allows you to filter the DataFrame and keep only the rows where a specific column matches any of the values in the provided list.

Here's an example using the isin() method to select rows from a DataFrame:

df[df['Name'].isin(lst)]
Name TotalMarks Grade Promoted 1 Doe 38 E False 2 Bill 63 B True 5 Ben 40 D True

str.contain()

The str.contains() method is very useful when you want to filter rows in a Pandas DataFrame based on partial matches or substrings in a specific column. It allows you to perform string matching operations and select rows that contain a specific substring.

Here's an example using the str.contains() method to filter rows in a DataFrame:

df[df['Name'].str.contains('B')]
Name TotalMarks Grade Promoted 2 Bill 63 B True 5 Ben 40 D True

Conclusion

You can use a list of values to select rows from a Pandas DataFrame by using either the isin() method or the str.contains() method. The isin() method allows you to filter rows based on exact matches, while the str.contains() method is useful when you want to filter rows based on partial matches or substrings in a specific column.