Python 在 Pandas DataFrame 中的任意位置搜索值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53979403/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:25:08  来源:igfitidea点击:

Search for a value anywhere in a pandas DataFrame

pythonpandasdataframe

提问by Josh Friedlander

This seems like a simple question, but I couldn't find it asked before (thisand thisare close but the answers aren't great).

这似乎是一个简单的问题,但我之前找不到它(thisthis很接近,但答案不是很好)。

The question is: if I want to search for a value somewherein my df (I don't know which column it's in) and return all rows with a match.

问题是:如果我想在我的 df某处搜索一个值(我不知道它在哪一列)并返回所有匹配的行。

What's the most Pandaic way to do it? Is there anything better than:

最 Pandaic 的方法是什么?有什么比:

for col in list(df):
    try:    
        df[col] == var
        return df[df[col] == var]
    except TypeError:
        continue 

?

?

回答by cs95

You can perform equality comparison on the entire DataFrame:

您可以对整个 DataFrame 执行相等比较:

df[df.eq(var1).any(1)]

Another option is using numpycomparison:

另一种选择是使用numpy比较:

df[(df.values.ravel() == var1).reshape(df.shape).any(1)]

回答by YOBEN_S

You should using isin, this is return the column , is want row check cold' answer :-)

你应该使用isin,这是返回列,是想要行检查冷'答案:-)

df.isin(['bal1']).any()
A        False
B         True
C        False
CLASS    False
dtype: bool

Or

或者

df[df.isin(['bal1'])].stack() # level 0 index is row index , level 1 index is columns which contain that value 
0  B    bal1
1  B    bal1
dtype: object

回答by ajay singh

You can try the code below:

你可以试试下面的代码:

import pandas as pd
x = pd.read_csv(r"filePath")
x.columns = x.columns.str.lower().str.replace(' ', '_')
y = x.columns.values
z = y.tolist()
print("Note: It take Case Sensitive Values.")
keyWord = input("Type a Keyword to Search: ")
try:
    for k in range(len(z)-1):
        l = x[x[z[k]].str.match(keyWord)]
        print(l.head(10))
        k = k+1
except:
    print("")