在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)]