How to check if Pandas column has value from list of string?

How to check if Pandas column has value from list of string?

To check if a pandas DataFrame column contains any value from a list of strings, you can use the isin() function. Here's how to do it:

  • Sample DataFrame:

Let's create a sample DataFrame for demonstration:

import pandas as pd data = { 'A': ['apple', 'banana', 'cherry', 'date', 'fig', 'grape'] } df = pd.DataFrame(data) 
  • Check if column contains values from a list:

Suppose we have the following list of strings:

fruits_to_check = ['apple', 'date', 'kiwi'] 

To check if the column 'A' has any values from this list:

df['in_list'] = df['A'].isin(fruits_to_check) 

This will create a new column in_list with boolean values, where True indicates the value in column 'A' is in fruits_to_check and False otherwise.

  • Display the result:
print(df) 

Output:

 A in_list 0 apple True 1 banana False 2 cherry False 3 date True 4 fig False 5 grape False 

The isin() function makes it very straightforward to check for membership in a list for each value in a pandas DataFrame column.


More Tags

flash-message google-apps-script-editor android-calendar extract-text-plugin playframework citations searching pageviews maxdate axios-cookiejar-support

More Programming Guides

Other Guides

More Programming Examples