Skip to main content
 首页 » 编程设计

python之Python中如何添加对应列名最大的列

2025年05月04日22artech

我有一个这样的数据框:

A1 A2 A3 ...A99 largest 
0   3  4  6      11   11 
1   1  8  2  ...  1    8 
. 
. 
. 

我使用以下方法创建了每行中包含最大值的列:

data['largest']=data.max(axis=1) 

但我也想得到一个列,其中包含具有最大数字的相应列名,如下所示:

    A1 A2 A3 ...A99 largest name 
0   3  4  6      11   11    A99 
1   1  8  2  ...  1    8    A2 
.                            . 
.                            . 
.                            . 

我试过'.idxmax'但给了我一个错误'reduction operation 'argmax' not allowed for this dtype',有人可以帮我吗?非常感谢。

请您参考如下方法:

使用DataFrame.idxmax与 DataFrame.assign添加 2 列而不相互推断:

df = data.assign(largest=data.max(axis=1), name=data.idxmax(axis=1)) 
print (df) 
   A1  A2  A3  A99  largest name 
0   3   4   6   11       11  A99 
1   1   8   2    1        8   A2 

或DataFrame.agg :

data[['largest','name']] = data.agg(['max','idxmax'], 1) 
print (data) 
   A1  A2  A3  A99 largest name 
0   3   4   6   11      11  A99 
1   1   8   2    1       8   A2 

编辑:

您只能选择数字列:

df1 = data.select_dtypes(np.number) 

或将列转换为数字:

df1 = data.astype(int) 

如果不工作 .astype 因为可能有一些非数值使用 to_numeric使用 errors='coerce' 转换有问题的值 no NaN:

df1 = data.apply(lambda x: pd.to_numeric(x, errors='coerce')) 

df = data.assign(largest=df1.max(axis=1), name=df1.idxmax(axis=1))