我有一个像这样的数据框:

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”,但给了我一个错误“此dtype不允许执行归约运算'argmax'”,有人可以帮我吗?非常感谢。

最佳答案

DataFrame.idxmaxDataFrame.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_numericerrors='coerce'一起用于转换有问题的值而没有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))

关于python - 如何在Python中添加包含最大列号的对应列名的列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56933916/

10-12 17:53
查看更多