Pandas - 在整个数据框中找到特定值

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

Pandas - find specific value in entire dataframe

pythonpandas

提问by Chloe

I have a dataframe and I want to search all columns for values that is text 'Apple'. I know how to do it with one column, but how can I apply this to ALL columns? I want to make it a function, so that next time I can directly use it to search for other values in other dateframes.

我有一个数据框,我想在所有列中搜索文本“Apple”的值。我知道如何用一列做到这一点,但如何将其应用于所有列?我想让它成为一个函数,以便下次我可以直接使用它来搜索其他日期帧中的其他值。

Thanks.

谢谢。

回答by James Marmarou

Take what you have for your single method and include in the for loop.

将您拥有的单一方法包含在 for 循环中。

for column in df:
    #your code here

回答by Mayank Porwal

Something like this:

像这样的东西:

In [1188]: df
Out[1188]: 
   id   name      n1
0   1   Zeke     may
1   2  Apple    maya
2   3      a   Apple
3   4   Maya       a
4   5  Derek  Mayank
5   6     an      is
6   7    the     the

Just have a check like:

只需检查一下:

In [1190]: df[df == 'Apple']
Out[1190]: 
   id   name     n1
0 NaN    NaN    NaN
1 NaN  Apple    NaN
2 NaN    NaN  Apple
3 NaN    NaN    NaN
4 NaN    NaN    NaN
5 NaN    NaN    NaN
6 NaN    NaN    NaN

OR

或者

In [1191]: df.where(df == 'Apple')
Out[1191]: 
   id   name     n1
0 NaN    NaN    NaN
1 NaN  Apple    NaN
2 NaN    NaN  Apple
3 NaN    NaN    NaN
4 NaN    NaN    NaN
5 NaN    NaN    NaN
6 NaN    NaN    NaN

This lets you search through all the columns of a dataframe.

这使您可以搜索数据框的所有列。

回答by Pratik Patel

import pandas library

导入Pandas库

import pandas as pd

Raw Data or URL of file

原始数据或文件的 URL

raw_data = {'first_name': ['Mihir', 'Mihir', 'Raju', 'Johan', 'Johan'],
               'last_name': ['Patel', 'Patel', 'Ali', 'Khan', 'Khan'], 
               'age': [42, 42, 36, 24, 53]}
df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age'])

Find The Value

找到价值

df.loc[df['first_name']=='Mihir']