Skip to main content
 首页 » 编程设计

python之获取一行中最大元素的列,写回df

2025年05月04日26www_RR

假设我有一个 DataFrame:

df = pd.DataFrame({'bar': [2, 1, 4, 10, 1, 1], 
                           'baz': [1, 2, 3, 1, 2, 3]}) 
 
bar baz 
0   2   1 
1   1   2 
2   4   3 
3   10  1 
4   1   2 
5   1   3 

我需要创建一个新列并在其中写入行中最大元素的列名:

    bar baz foo 
la  2   1   bar 
qw  2   1   bar 
re  2   3   baz 
gf  4   3   bar 
hg  10  1   bar 
ds  1   2   baz 
ds  1   3   baz 

至少,我是这样提取这些名字的:

a = hours.as_matrix() 
for i in a: 
    print(hours.columns[i.argmax()]) 

但是,我不能把它写入DataFrame,因为索引不是整数

请您参考如下方法:

你可以使用DataFrame.idxmax(axis=1)

In [101]: df 
Out[101]: 
    bar  baz 
la    2    1 
qw    2    1 
re    2    3 
gf    4    3 
hg   10    1 
ds    1    2 
ds    1    3 
 
In [102]: df['foo'] = df.idxmax(1) 
 
In [103]: df 
Out[103]: 
    bar  baz  foo 
la    2    1  bar 
qw    2    1  bar 
re    2    3  baz 
gf    4    3  bar 
hg   10    1  bar 
ds    1    2  baz 
ds    1    3  baz