Python - Pandas: number/index of the minimum value in the given row

倖福魔咒の 提交于 2021-02-10 13:49:13

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/54513371/python-pandas-number-index-of-the-minimum-value-in-the-given-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!