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

标签 python pandas dataframe max data-science

我有一个这样的数据框:

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.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_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))

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

相关文章:

python - 按行和列获取单元格的值

python - pandas 函数将行数据转置为列

python - 如何获取 Pandas 中 groupby 对象中每个项目的索引?

r - 比较两个数据集并找出通用名称

python - 在条件下使用排序切片 Pandas Dataframe

python - 如何将字符串中每个单词的首字母大写?

python - 如何在 python 中用整数制作网格?

python - 如何从 DataFrame 创建整数列表列表?

python,pandas,按条件删除行

R:加快将巨大的 data.frame 写入文本文件的速度?