biological-sprout
biological-sprout

Reputation: 11

Find rows in a DataFrame that match

Suppose make a data frame with pandas

df = pandas.DataFrame({"a":[1,2,3],"b":[3,4,5]})

Now I have a series

s = pandas.Series([1,3], index=['a','b'])

OK, finally, my question is how can I know s is a item in df especially I need to consider performance?

ps: It's better to return True or False when test s in or not in df.

Upvotes: 1

Views: 58

Answers (1)

cs95
cs95

Reputation: 402413

You want

df.eq(s).all(axis=1).any()
# True

We start with a row-wise comparison,

df.eq(s)

       a      b
0   True   True
1  False  False
2  False  False

Find all rows which match fully,

df.eq(s).all(axis=1)

0     True
1    False
2    False
dtype: bool

Return True if any matches were found,

df.eq(s).all(axis=1).any()
# True

Upvotes: 1

Related Questions