如何 return 列标题,其中该行包含 Pandas Dataframe 中的最大值

How to return the column title wherein the row contains the greatest value in Pandas Dataframe

我正在开发一个 Python 项目,它有一个像这样的 DataFrame:

data = {'AAA':  [3, 8, 2, 1],
        'BBB':  [5, 4, 7, 2],
        'CCC':  [2, 5, 6, 4]}
df = pd.DataFrame(data)

这导致:

AAA BBB CCC
0 3 5 2
1 8 4 5
2 2 7 6
3 1 2 4

任务包括生成以下 DataFrame:

AAA BBB CCC Role
0 3 5 2 BBB
1 8 4 5 AAA
2 2 7 6 BBB
3 1 2 4 CCC

其中“角色”列元素是在其所在行中具有最高值的列 headers。

你能帮我推荐一个解决这个任务的代码吗?

您可以在轴上使用 idxmax 方法:

df['Role'] = df.idxmax(axis=1)

输出:

   AAA  BBB  CCC  Role
0    3    5    2  BBB
1    8    4    5  AAA
2    2    7    6  BBB
3    1    2    4  CCC