2

I have one pandas dataframe, with one row and multiple columns.

I want to get the column number/index of the minimum value in the given row.

The code I found was: df.columns.get_loc('colname')

The above code asks for a column name. My dataframe doesn't have column names. I want to get the column location of the minimum value.

Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80
Ridhima Kumar
  • 151
  • 3
  • 14

1 Answers1

5

Use argmin with converting DataFrame to array by values, only necessary only numeric data:

df = pd.DataFrame({
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[-5,3,6,9,2,-4]

})

print (df)
   B  C  D  E
0  4  7  1 -5
1  5  8  3  3
2  4  9  5  6
3  5  4  7  9
4  5  2  1  2
5  4  3  0 -4

df['col'] = df.values.argmin(axis=1)
print (df)
   B  C  D  E  col
0  4  7  1 -5    3
1  5  8  3  3    2
2  4  9  5  6    0
3  5  4  7  9    1
4  5  2  1  2    2
5  4  3  0 -4    3
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252