Skip to content Skip to sidebar Skip to footer

Getting (index, Column) Pairs For True Elements Of A Boolean Dataframe In Pandas

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 DataFrame

Solution 1:

x[x > 0].stack().index.tolist()

Solution 2:

My approach uses MultiIndex:

#make it a multi-indexed Seriesstacked = y.stack()

#restrict to where it's Truetrue_stacked = stacked[stacked]

#get index as a list of tuplesresult = true_stacked.index.tolist()

Solution 3:

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()]

Post a Comment for "Getting (index, Column) Pairs For True Elements Of A Boolean Dataframe In Pandas"