You can use the following methods to check if a particular value exists in a column of a pandas DataFrame:
Method 1: Check if One Value Exists in Column
22 in df['my_column'].values
Method 2: Check if One of Several Values Exist in Column
df['my_column'].isin([44, 45, 22]).any()
The following examples show how to use each method in practice with the following DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 'points': [18, 22, 19, 14, 14, 11, 20, 28], 'assists': [5, 7, 7, 9, 12, 9, 9, 4], 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame print(df) team points assists rebounds 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 4 E 14 12 6 5 F 11 9 5 6 G 20 9 9 7 H 28 4 12
Example 1: Check if One Value Exists in Column
The following code shows how to check if the value 22 exists in the points column:
#check if 22 exists in the 'points' column 22 in df['points'].values True
The output returns True, which tells us that the value 22 does exist in the points column.
We can use the same syntax with string columns as well.
For example, the following code shows how to check if the string ‘J’ exists in the team column:
#check if 'J' exists in the 'team' column 'J' in df['team'].values False
The output returns False, which tells us that the string ‘J’ does not exist in the team column.
Example 2: Check if One of Several Values Exist in Column
The following code shows how to check if any of the values in the list [44, 45, 22] exist in the points column:
#check if 44, 45 or 22 exist in the 'points' column df['points'].isin([44, 45, 22]).any() True
The output returns True, which tells us that at least one of the values in the list [44, 45, 22] exists in the points column of the DataFrame.
We can use the same syntax with string columns as well.
For example, the following code shows how to check if any string in the list [‘J’, ‘K’, ‘L’] exists in the team column:
#check if J, K, or L exists in the 'team' column df['team'].isin(['J', 'K', 'L']).any() False
The output returns False, which tells us that none of the strings in the list exist in the team column.
Additional Resources
The following tutorials explain how to perform other common operations in pandas:
How to Drop Rows in Pandas DataFrame Based on Condition
How to Filter a Pandas DataFrame on Multiple Conditions
How to Use “NOT IN” Filter in Pandas DataFrame