在 Pandas DataFrame 中查找字符串值的索引

Ben*_*Ben 5 python pandas

如何识别 DataFrame 中的哪些列包含特定字符串'foo'

示例数据帧:

>>> import pandas as pd
>>> df = pd.DataFrame({'A':[10,20,42], 'B':['foo','bar','blah'],'C':[3,4,5], 'D':['some','foo','thing']})
Run Code Online (Sandbox Code Playgroud)

我想找到BD这里。

我可以搜索数字:

如果我正在寻找一个数字(例如 42)而不是一个字符串,我可以生成一个布尔掩码,如下所示:

>>> ~(df.where(df==42)).isnull().all()

A     True
B    False
C    False
D    False
dtype: bool
Run Code Online (Sandbox Code Playgroud)

但不是字符串:

>>> ~(df.where(df=='foo')).isnull().all()

TypeError: Could not compare ['foo'] with block values
Run Code Online (Sandbox Code Playgroud)

如果可能,我不想遍历每一列和每一行(我的实际数据比这个例子大得多)。感觉应该有一个简单有效的方法。

我怎样才能做到这一点?

Div*_*kar 4

使用底层数组数据的一种方法 -

df.columns[(df.values=='foo').any(0)].tolist()
Run Code Online (Sandbox Code Playgroud)

样本运行 -

In [209]: df
Out[209]: 
    A     B  C      D
0  10   foo  3   some
1  20   bar  4    foo
2  42  blah  5  thing

In [210]: df.columns[(df.values=='foo').any(0)].tolist()
Out[210]: ['B', 'D']
Run Code Online (Sandbox Code Playgroud)

如果您只是寻找列掩码 -

In [205]: (df.values=='foo').any(0)
Out[205]: array([False,  True, False,  True], dtype=bool)
Run Code Online (Sandbox Code Playgroud)