在pandas DataFrame中的任何位置搜索值 [英] Search for a value anywhere in a pandas DataFrame
本文介绍了在pandas DataFrame中的任何位置搜索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这似乎是一个简单的问题,但是我之前找不到它(此和此很接近,但答案不好)。
This seems like a simple question, but I couldn't find it asked before (this and this are close but the answers aren't great).
问题是:如果我想在df中搜索某处的值(我不知道它在哪一列中),返回所有具有匹配项的行。
The question is: if I want to search for a value somewhere in my df (I don't know which column it's in) and return all rows with a match.
最古怪的方式是什么?还有什么比以下更好的东西了:
What's the most Pandaic way to do it? Is there anything better than:
for col in list(df):
try:
df[col] == var
return df[df[col] == var]
except TypeError:
continue
?
推荐答案
您可以在整个DataFrame上执行相等比较:
You can perform equality comparison on the entire DataFrame:
df[df.eq(var1).any(1)]
另一个选择是使用 numpy
比较:
Another option is using numpy
comparison:
df[(df.values.ravel() == var1).reshape(df.shape).any(1)]
这篇关于在pandas DataFrame中的任何位置搜索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文