How to filter a DataFrame based on a list of strings in python pandas
To filter a DataFrame based on a list of strings, you can use the .isin() method combined with the operator.
To filter a DataFrame based on a list of strings, you can use theĀ .isin() method combined with the [] operator. The isin() method returns a Boolean mask indicating whether each element in the DataFrame is contained in the list of strings or not. You can then use this mask to filter the DataFrame.
For example, suppose you have a DataFrame df:
import pandas as pd
df = pd.DataFrame({'A': ['apple', 'banana', 'orange', 'apple', 'banana'], 'B': [1, 2, 3, 4, 5], 'C': [6, 7, 8, 9, 10]})
print(df)This will produce the following output:
A B C0 apple 1 61 banana 2 72 orange 3 83 apple 4 94 banana 5 10Now suppose you have a list of strings:
fruits = ['apple', 'orange']You can use the isin() method to filter the DataFrame based on this list of strings like this:
filtered_df = df[df['A'].isin(fruits)]print(filtered_df)This will return a new DataFrame with only the rows where the 'A' column is equal to either 'apple' or 'orange':
A B C0 apple 1 62 orange 3 83 apple 4 9You can also use the isin() method to filter multiple columns at once. For example:
filtered_df = df[df['A'].isin(fruits) & df['B'].isin([1, 3])]print(filtered_df)This will return a new DataFrame with only the rows where the 'A' column is equal to either 'apple' or 'orange', and the 'B' column is equal to either 1 or 3:
A B C0 apple 1 62 orange 3 8
Comments