Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append the column names corresponding to the minimum row values of a dataframe to create a new dataframe

I have the following dataframe

import pandas as pd
data = [[5,4,3,2,6,8], [9,1,5,4,8,6], [7,6,8,1,2,4], [9,6,5,4,8,3]]
df = pd.DataFrame(data, columns=['Col1','Col2','Col3','Col4','Col5','Col6'])
df

I am trying to display the minimum value of each row along with the column name.

df=df.min(axis=1)
df

output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2
1
1
3

But how can I append the column names corresponding to those minimum value of rows?

My expected output is

2    col4
1    col2
1    col4
3    col6

>Solution :

You can try:

df[['Col', 'Value']] = df.apply(lambda x: [idx:=x.idxmin(), x[idx]], axis=1, result_type='expand')
print(df)

Prints:

   Col1  Col2  Col3  Col4  Col5  Col6   Col  Value
0     5     4     3     2     6     8  Col4      2
1     9     1     5     4     8     6  Col2      1
2     7     6     8     1     2     4  Col4      1
3     9     6     5     4     8     3  Col6      3

If you want only the Col, Value:

print(df[['Col', 'Value']].set_index('Value'))

Prints:

        Col
Value      
2      Col4
1      Col2
1      Col4
3      Col6
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading