Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting list of all columns corresponding to maximum value in each row in a Dataframe

How to get list of all columns corresponding to maximum value in each row in a Dataframe? For example, if I have this dataframe,

df = pd.DataFrame({'a':[12,34,98,26],'b':[12,87,98,12],'c':[11,23,43,1]})

    a   b   c
0  12  12  11
1  34  87  23
2  98  98  43
3  26  12   1

I want to make another dataframe as shown below,

0  [a,b] 
1  [b] 
2  [a,b]
3  [a]

How can I do that?

like image 450
User1917931829 Avatar asked Jan 28 '26 10:01

User1917931829


1 Answers

You could try these codes (bot approaches do the same):

max_cols_df = pd.DataFrame({"max_cols": [list(df[df==mv].iloc[i].dropna().index) for i, mv in enumerate(df.max(axis=1))]})
max_cols_df = pd.DataFrame({"max_cols": [list(df.iloc[i][v].index) for i, v in df.eq(df.max(axis=1), axis=0).iterrows()]})

max_cols_df 
----------------
    max_cols
0   [a, b]
1   [b]
2   [a, b]
3   [a]
----------------

But I think you asked a related question to another post and cannot upgrade pandas. Therefore, the second could throw an error.

like image 96
ko3 Avatar answered Jan 29 '26 22:01

ko3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!