pandas :检查行是否存在某些值 [英] Pandas: Check if row exists with certain values
问题描述
我有一个这样的二维(或更多)熊猫DataFrame:
I have a two dimensional (or more) pandas DataFrame like this:
>>> import pandas as pd
>>> df = pd.DataFrame([[0,1],[2,3],[4,5]], columns=['A', 'B'])
>>> df
A B
0 0 1
1 2 3
2 4 5
现在假设我有一个像np.array([2,3])
这样的numpy数组,并想检查df
中是否有任何与我的数组内容匹配的行.这里的答案显然应该是正确的,但是例如. np.array([1,2])
应该返回false,因为没有行同时在A列和B列中都包含2.
Now suppose I have a numpy array like np.array([2,3])
and want to check if there is any row in df
that matches with the contents of my array. Here the answer should obviously true but eg. np.array([1,2])
should return false as there is no row with both 1 in column A and 2 in column B.
确定这很容易,但是现在看不到.
Sure this is easy but don't see it right now.
推荐答案
事实证明这确实很容易,以下是在这里完成的工作:
Turns out it is really easy, the following does the job here:
>>> ((df['A'] == 2) & (df['B'] == 3)).any()
True
>>> ((df['A'] == 1) & (df['B'] == 2)).any()
False
也许有人想出了一个更好的解决方案,它允许直接传递数组和要匹配的列列表.
Maybe somebody comes up with a better solution which allows directly passing in the array and the list of columns to match.
请注意,df['A'] == 2
周围的括号不是可选的,因为&
运算符的绑定强度与==
运算符相同.
Note that the parenthesis around df['A'] == 2
are not optional since the &
operator binds just as strong as the ==
operator.
这篇关于 pandas :检查行是否存在某些值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!