Skip to content Skip to sidebar Skip to footer

Most Efficient Way To Return Column Name In A Pandas Df

I have a pandas df that contains 4 different columns. For every row theres a value thats of importance. I want to return the Column name where that value is displayed. So for the d

Solution 1:

Use DataFrame.dot:

df.astype(bool).dot(df.columns).str.cat(sep=',')

Or,

','.join(df.astype(bool).dot(df.columns))

'A,C,B,A'

Or, as a list:

df.astype(bool).dot(df.columns).tolist()
['A', 'C', 'B', 'A']

...or a Series:

df.astype(bool).dot(df.columns)

0A1C2B3Adtype: object

Post a Comment for "Most Efficient Way To Return Column Name In A Pandas Df"