pandas 中最大值的列标签 [英] Column label of max in pandas

查看:39
本文介绍了 pandas 中最大值的列标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 Pandas 数据框中提取行中的最大值和贡献列标签.例如,

I am trying to extract maximum value in row and contributing column label from pandas dataframe. For example,

       A B C D
index 
x     0 1 2 3
y     3 2 1 0

我期待以下输出,

      A  B  C  D  Maxv Con
index 
x     0  1  2  3  3  D   
y     3  2  1  0  3  A

我尝试了以下方法,

df['Maxv'] = df.apply(max,axis=1)
df['Con'] = df.idxmax(axis='rows')

它只返回最大列和 Con 列的NaN".这里的错误是什么?

It returned only the max column and 'NaN' for Con column. What is the error here?

提前致谢.

AP

推荐答案

需要 axis='columns'axis=1DataFrame.idxmax:

Need axis='columns' or axis=1 in DataFrame.idxmax:

df['Con'] = df.idxmax(axis='columns')
print (df)
       A  B  C  D  Maxv Con
index                      
x      0  1  2  3     3   D
y      3  2  1  0     3   A

或者:

df['Con'] = df.idxmax(axis=1)
print (df)
       A  B  C  D  Maxv Con
index                      
x      0  1  2  3     3   D
y      3  2  1  0     3   A

你得到 NaNs,因为数据没有与 index 对齐:

You get NaNs, because data are not align to index:

print (df.idxmax(axis='rows'))
A    y
B    y
C    x
D    x
dtype: object 

这篇关于 pandas 中最大值的列标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆