Getting (index, column) pairs for True elements of a boolean DataFrame in Pandas

后端 未结 3 1226
清歌不尽
清歌不尽 2020-12-15 07:46

Say I have a Pandas DataFrame and I want to obtain a list of tuples of the form [(index1, column1), (index2, column2) ...] describing the locations of all elements of the Da

相关标签:
3条回答
  • 2020-12-15 07:55

    If you want a single tuple for each row index:

    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()]
    
    0 讨论(0)
  • 2020-12-15 07:59

    My approach uses 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()
    
    0 讨论(0)
  • 2020-12-15 08:09
    x[x > 0].stack().index.tolist()
    
    0 讨论(0)
提交回复
热议问题