【问题标题】:How to get column index which is matching with specific value in Pandas?如何获取与 Pandas 中特定值匹配的列索引?
【发布时间】:2023-02-01 23:13:02
【问题描述】:

我有如下数据框。

     0      1      2      3      4      5      6      7
    True  False  False  False  False  False  False  False
    [1 rows * 8 columns]

如您所见,第一列有一个 True 值。

因此,我想获取数据框中的 0 索引,即 True 元素。 在其他情况下,第 4 列索引中有 True,那么我想获取 4,因为第 4 列具有以下数据框的 True 值。

     0      1      2      3      4      5      6      7
    False  False  False  False  True  False  False  False
    [1 rows * 8 columns]

我试图用谷歌搜索它,但没有得到我想要的。 并且对于假设,案例中没有指定列名。

期待您的帮助。

谢谢。

【问题讨论】:

  • 你总是只有一排吗?

标签: python pandas


【解决方案1】:

如果你想要每个字段都是真的:

cols_true = []
for idx, row in df.iterrows():
    for i in cols:
        if row[i]:
            cols_true.append(i)
print(cols_true)

【讨论】:

    【解决方案2】:

    使用布尔索引:

    df.columns[df.iloc[0]]
    

    输出:

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

    或者numpy.where

    np.where(df)[1]
    

    【讨论】:

      【解决方案3】:

      IIUC,你在找idxmax

      >>> df
            0      1      2      3      4      5      6      7
      0  True  False  False  False  False  False  False  False
      
      >>> df.idxmax(axis=1)
      0    0
      dtype: object
      
      >>> df
             0      1      2      3     4      5      6      7
      0  False  False  False  False  True  False  False  False
      
      >>> df.idxmax(axis=1)
      0    4
      dtype: object
      

      警告:如果所有值都是False,Pandas 返回第一个索引,因为索引 0 是最高值的最低索引:

      >>> df
             0      1      2      3      4      5      6      7
      0  False  False  False  False  False  False  False  False
      
      >>> df.idxmax(axis=1)
      0    0
      dtype: object
      

      解决方法:将False替换为np.nan

      >>> df.replace(False, np.nan).idxmax(axis=1)
      0   NaN
      dtype: float64
      

      【讨论】:

      • @大本钟。谢谢我修好了。
      【解决方案4】:

      您可能希望通过列本身(在本例中为0)对数据框的索引进行索引,如下所示:

      df.index[df[0]]
      

      你会得到:

      Int64Index([0], dtype='int64')
      

      【讨论】:

        猜你喜欢
        • 2014-03-15
        • 1970-01-01
        • 2018-01-20
        • 1970-01-01
        • 2018-10-01
        • 1970-01-01
        • 2021-11-13
        • 2016-12-07
        • 2014-03-07
        相关资源
        最近更新 更多