【问题标题】:Get (index,column) pair where the value is True获取值为 True 的 (index,column) 对
【发布时间】:2022-10-25 20:46:45
【问题描述】:

假设我有一个数据框df

  a        b     c
0 False  True   True
1 False  False  False
2 True   True   False
3 False   False  False

我想要所有 (index,column) 对,例如 (0,"b"),(0,"c),(2,"a"),(2,"b") True 值所在的位置。

有没有办法做到这一点,而无需遍历索引或列?

【问题讨论】:

    标签: pandas


    【解决方案1】:

    假设输入中的布尔值,您可以使用:

    df.where(df).stack().index.to_list()
    

    输出:

    [(0, 'b'), (0, 'c'), (2, 'a'), (2, 'b')]
    

    【讨论】:

      【解决方案2】:

      让我们试试np.where

      r, c = np.where(df)
      [*zip(df.index[r], df.columns[c])]
      

      [(0, 'b'), (0, 'c'), (2, 'a'), (2, 'b')]
      

      【讨论】:

        【解决方案3】:
        df1.stack().to_frame('col1').query('col1').index.tolist()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-12-24
          • 2011-04-30
          • 1970-01-01
          • 2017-06-14
          • 1970-01-01
          • 2021-11-26
          • 1970-01-01
          • 2018-08-13
          相关资源
          最近更新 更多