How to check if a Pandas Dataframe column contains a value?

Viewed 2453

I'd like to check if a pandas.DataFrame column contains a specific value. For instance, this toy Dataframe has a "h" in column "two":

import pandas as pd
df = pd.DataFrame(
    np.array(list("abcdefghi")).reshape((3, 3)),
    columns=["one", "two", "three"]
)
df
  one two three
0   a   b     c
1   d   e     f
2   g   h     i

But surprisingly,

"h" in df["two"]

evaluates to False.

My question is: What's the clearest way to find out if a DataFrame column (or pandas.Series in general) contains a specific value?

1 Answers

df["two"] is a pandas.Series which looks like this:

0    b
1    e
2    h

It turns out, the in operator checks the index, not the values. I.e.

2 in df["two"]

evaluates to True

So one has to explicitly check for the values like this:

"h" in df["two"].values

This evaluates to True.

Related