Reputation: 458
I have a pandas Series and I want to test if it corresponds exactly to a row of a pandas DataFrame
s in df
==> True
where s = pd.Series({'a': 1, 'b': 2})
and df = pd.DataFrame({'a': [1,2,3], 'b': [2,1,3]})
s in df
==> False
where s = pd.Series({'a': 1, 'b': 2})
and df = pd.DataFrame({'a': [2,1,3], 'b': [1,3,4]})
not df[(df['a'] == s['a']) & (df['b'] == s['b'])].empty
Upvotes: 1
Views: 114
Reputation: 862511
One idea is compare by DataFrame.eq
, then test if at least one match by DataFrame.all
and then test by Series.any
:
Here is added DataFrame.reindex
for filter columns only by Series
s
:
df = pd.DataFrame({'a': [1,2,3], 'b': [2,1,3], 'c': [4,5,48]})
print (df)
a b c
0 1 2 4
1 2 1 5
2 3 3 48
s = pd.Series({'a': 1, 'b': 2})
print (df.reindex(s.index, axis=1))
a b
0 1 2
1 2 1
2 3 3
print (df.reindex(s.index, axis=1).eq(s))
a b
0 True True
1 False False
2 False False
print (df.reindex(s.index, axis=1).eq(s).all(axis=1))
0 True
1 False
2 False
dtype: bool
print (df.reindex(s.index, axis=1).eq(s).all(axis=1).any())
True
Upvotes: 2