简体   繁体   English

如何检查 pandas.DataFrame 中的某个值在哪一列?

[英]How to check in which column is certain value in pandas.DataFrame?

I have DataFrame in Python like below:我在 Python 中有 DataFrame ,如下所示:

df = pd.DataFrame({"col1"  : ["a", "b", "c"], "col2" : ["a", "d", "e"], "col3" : ["r", "t" , "g"]})

And I would like to check in which columns is value "a" (of course in "col1" and "col2").我想检查哪些列的值是“a”(当然在“col1”和“col2”中)。 How can I check it?我怎样才能检查它?

(df=='a').any()

col1     True
col2     True
col3    False

If need columns names in list compare all values by DataFrame.eq with DataFrame.any for check if at least one True (match) per columns, last filter columns names:如果需要列表中的列名比较DataFrame.eqDataFrame.any的所有值,以检查每列是否至少有一个True (匹配),最后过滤列名:

c = df.columns[df.eq('a').any()].tolist()
print (c)
['col1', 'col2']

If need filter columns to new DataFrame use DataFrame.loc :如果需要过滤列到新的DataFrame使用DataFrame.loc

df1 = df.loc[:, df.eq('a').any()]
print (df1)
  col1 col2
0    a    a
1    b    d
2    c    e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM