【问题标题】:Getting (index, column) pairs for True elements of a boolean DataFrame in Pandas在 Pandas 中获取布尔 DataFrame 的 True 元素的(索引,列)对
【发布时间】:2014-11-10 22:21:34
【问题描述】:

假设我有一个 Pandas DataFrame,我想获得一个 [(index1, column1), (index2, column2) ...] 形式的元组列表,描述 DataFrame 的所有元素在某些条件下的位置真的。例如:

x = pd.DataFrame(np.random.normal(0, 1, (4,4)), index=['a', 'b', 'c', 'd'],
                 columns=['e', 'f', 'g', 'h'])
x


     e           f           g           h
a   -1.342571   -0.274879   -0.903354   -1.458702
b   -1.521502   -1.135800   -1.147913   1.829485
c   -1.199857   0.458135    -1.993701   -0.878301
d   0.485599    0.286608    -0.436289   -0.390755

y = x > 0

有没有办法获得:

x.loc[y]

返回:

[(b, h), (c,f), (d, e), (d,f)]

或类似的?显然,我可以做到:

postup = []
for i in x.index:
    for j in x.columns:
        if x.loc[i, j] > 0:
            postup.append((i, j))

但我想可能/已经实现了更好的东西。在 matlab 中,函数 find 与 sub2ind 结合使用。

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    x[x > 0].stack().index.tolist()
    

    【讨论】:

      【解决方案2】:

      我的方法使用MultiIndex

      #make it a multi-indexed Series
      stacked = y.stack()
      
      #restrict to where it's True
      true_stacked = stacked[stacked]
      
      #get index as a list of tuples
      result = true_stacked.index.tolist()
      

      【讨论】:

        【解决方案3】:

        如果您希望每个行索引都有一个元组:

        import pandas as pd
        import numpy as np
        df = pd.DataFrame(np.random.normal(0, 1, (4,4)), index=['a', 'b', 'c', 'd'], columns=['e', 'f', 'g', 'h'])
        
        # build column replacement
        column_dict = {}
        for col in [{col: {True: col}} for col in df.columns]:
            column_dict.update(col)
        
        # replace where > 0
        df = (df>0).replace(to_replace=column_dict)
        
        # convert to tuples and drop 'False' values
        [tuple(y for y in x if y != False) for x in df.to_records()]
        

        【讨论】:

          猜你喜欢
          • 2019-02-09
          • 1970-01-01
          • 1970-01-01
          • 2022-06-27
          • 1970-01-01
          • 1970-01-01
          • 2018-08-18
          • 2012-10-16
          • 1970-01-01
          相关资源
          最近更新 更多