【问题标题】:Get column name which contains a specific value at any rows in python pandas获取包含python pandas中任何行的特定值的列名
【发布时间】:2018-11-28 03:21:54
【问题描述】:

我想根据 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)`

然后输出出现错误:

Traceback (most recent call last): NameError: name 'APPLE' is not defined

非常感谢你们的任何帮助,谢谢。 . .

【问题讨论】:

    标签: python pandas dataframe input


    【解决方案1】:

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

    df.columns[df.isin(['APPLE']).any()]  # df.isin([response])
    

    或者,

    df.columns[df.eq(response).any()]
    

    Index(['A'], dtype='object')
    

    这里是DataFrame.evalnp.logical_or 的迂回方式(你是否在列上循环):

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

    【讨论】:

    • 这是一个很好的将np.logical_or.reduce() 与 Pandas 一起使用的例子! +1
    【解决方案2】:

    首先,您的错误原因。对于pd.DataFrame.query,与常规比较一样,您需要用引号将字符串括起来。所以这会起作用(注意一对" 引号):

    response = input("input")
    
    for i in df.columns:
        if not df.query(i + '=="' + str(response) + '"').empty:
            print(i)
    
    inputAPPLE
    A
    

    接下来,您可以通过pd.DataFrame.any 提取索引和/或列。 coldspeed's solution 在这里很好,我将展示如何使用相似的语法来提取行和列标签。

    # columns
    print(df.columns[(df == response).any(1)])
    Index(['A'], dtype='object')
    
    # rows
    print(df.index[(df == response).any(0)])
    Int64Index([0], dtype='int64')
    

    请注意,在这两种情况下,您都会得到Index 对象。代码的不同之处仅在于提取的属性和pd.DataFrame.anyaxis 参数。

    【讨论】:

      猜你喜欢
      • 2018-11-13
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 2023-02-17
      • 2020-07-23
      相关资源
      最近更新 更多