Conditional doesn´t return True when it is proved that it is in Python

Viewed 40

I am trying to find if an integer value exists in a DataFrame column:

When I try df[df['COLUMN'] == 196930], I get the rows of the DataFrame containing the column value as expected.

However, I am running into problems trying to use a conditional to find if the value is the column (and ultimately perform an action based on this condition):

if 196930 in df['COLUMN']:
    ...
    ...
    ...

It returns False even though this integer clearly exists in the DataFrame column, and I don't understand why this is happening. Thank you in advance.

1 Answers

df['COLUMN'] returns a pandas Series. For the in operator, the Series class returns true if there is a label matching the operand. When you write if 196930 in df['COLUMN'] you are testing if the Series contains the label 196930.

You can test if the column contains the value like this:

if (df['COLUMN'] == 196930).any(): ...

if df['COLUMN'].eq(196930).any(): ...
Related