获取列名,该列名在python pandas的任何行中都包含特定值

wh1*_*112 5 python input dataframe pandas

我想从整个数据库中获取列名(假设数据库包含超过100行,其中50列以上)基于熊猫中特定列中包含的特定值。

在Bkmm3(来自印度的成员)的帮助下,我在数字术语上取得了成功,但在字母术语上却失败了。我尝试的方式是这样的:

df = pd.DataFrame({'A':['APPLE','BALL','CAT'],
                    'B':['ACTION','BATMAN','CATCHUP'],
                    'C':['ADVERTISE','BEAST','CARTOON']})
response = input("input")
for i in df.columns: if(len(df.query(i + '==' + str(response))) > 0):
print(i)`
Run Code Online (Sandbox Code Playgroud)

然后输出出现错误:

Traceback (most recent call last): NameError: name 'APPLE' is not defined
Run Code Online (Sandbox Code Playgroud)

谢谢大家的任何帮助,谢谢。。。

cs9*_*s95 8

isin/ eq适用于DataFrames,您可以将其100%向量化:

df.columns[df.isin(['APPLE']).any()]  # df.isin([response])
Run Code Online (Sandbox Code Playgroud)

要么,

df.columns[df.eq(response).any()]
Run Code Online (Sandbox Code Playgroud)

Index(['A'], dtype='object')
Run Code Online (Sandbox Code Playgroud)

这是DataFrame.evaland和np.logical_or(要在列上循环)的回旋方式:

df.columns[
    np.logical_or.reduce(
        [df.eval(f"{repr(response)} in {i}") for i in df]
)]
Index(['A'], dtype='object')
Run Code Online (Sandbox Code Playgroud)