Python Pandas:检查是否存在具有特定值的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24761133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: Check if row exists with certain values
提问by Robin
I have a two dimensional (or more) pandas DataFrame like this:
我有一个像这样的二维(或更多)pandas DataFrame:
>>> 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
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.
现在假设我有一个类似的 numpy 数组,np.array([2,3])
并想检查是否有任何行df
与我的数组的内容匹配。这里的答案显然应该是正确的,但例如。np.array([1,2])
应该返回 false,因为 A 列中没有包含 1 且 B 列中包含 2 的行。
Sure this is easy but don't see it right now.
当然这很容易,但现在还没有看到。
采纳答案by Robin
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.
也许有人想出了一个更好的解决方案,它允许直接传入数组和要匹配的列列表。
Note that the parenthesis around df['A'] == 2
are not optional since the &
operator binds just as strong as the ==
operator.
请注意,周围的括号df['A'] == 2
不是可选的,因为&
运算符绑定与运算符一样强==
。
回答by acushner
an easier way is:
更简单的方法是:
a = np.array([2,3])
(df == a).all(1).any()
回答by sparrow
If you also want to return the index where the matches occurred:
如果您还想返回匹配发生的索引:
index_list = df[(df['A'] == 2)&(df['B'] == 3)].index.tolist()