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:
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