Use a list of values to select rows from a pandas dataframe
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']
You can use isin([]) method to select rows from 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()
isin() is ideal if you have a list of exact matches in DataFrame , but if you have a list of partial matches or substrings to look for, you can filter using the str.contains() method.
df[df['Name'].str.contains('B')]
Name TotalMarks Grade Promoted
2 Bill 63 B True
5 Ben 40 D True
Related Topics
- Creating an empty Pandas DataFrame
- How to Check if a Pandas DataFrame is Empty
- How to check if a column exists in Pandas Dataframe
- How to delete column from pandas DataFrame
- How to select multiple columns from Pandas DataFrame
- Selecting multiple columns in a Pandas dataframe based on condition
- Selecting rows in pandas DataFrame based on conditions
- How to Drop rows in DataFrame by conditions on column values
- Rename column in Pandas DataFrame
- Get a List of all Column Names in Pandas DataFrame
- How to add new columns to Pandas dataframe?
- Change the order of columns in Pandas dataframe
- Concatenate two columns into a single column in pandas dataframe
- How to count the number of rows and columns in a Pandas DataFrame
- How to iterate over rows in a DataFrame in Pandas
- How to drop rows/columns of Pandas DataFrame whose value is NaN
- How to Export Pandas DataFrame to a CSV File
- Convert list of dictionaries to a pandas DataFrame
- How to set a particular cell value in pandas DataFrame