【问题标题】:Obtain the pandas dataframe column names in a list when one cell value equals to a specific string当一个单元格值等于特定字符串时,获取列表中的 pandas 数据框列名
【发布时间】:2021-08-26 17:11:30
【问题描述】:

我有一个大约 20-30 列的 pandas 数据框。当一个单元格值等于字符串“Fail”时,我想获取列表中的列名。

数据框如下所示:

    Column_1 Column_2 ... Column_30
0      Pass   Pass          Fail
1      Pass   Pass          Pass
2      Fail   Pass          Pass
3      Pass   Pass          Pass
4      Pass   Pass          Pass
..

预期的结果是这样的[Column_1, Column 30]

【问题讨论】:

    标签: python pandas list dataframe


    【解决方案1】:

    我认为这应该可以解决问题

    df.columns[(df=='Fail').any(axis=0)]
    

    这将为您提供在其行中至少包含一个“失败”的每一列的列名称作为 pandas.Index。如果一定是列表,在最后加上.tolist()即可。

    【讨论】:

      【解决方案2】:

      您可以进行包含值检查的列表推导:

      [col for col in df.columns if 'Fail' in df[col].values]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-10
        • 2022-11-16
        • 1970-01-01
        • 1970-01-01
        • 2021-01-04
        • 2021-10-15
        相关资源
        最近更新 更多