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

后端 未结 3 1231
清歌不尽
清歌不尽 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()]
    

提交回复
热议问题