查找每个列的最大值

2024-06-10 02:20:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的数据框:

In [7]:
frame.head()
Out[7]:
Communications and Search   Business    General Lifestyle
0   0.745763    0.050847    0.118644    0.084746
0   0.333333    0.000000    0.583333    0.083333
0   0.617021    0.042553    0.297872    0.042553
0   0.435897    0.000000    0.410256    0.153846
0   0.358974    0.076923    0.410256    0.153846

在这里,我想问一下如何获取列名,列名对每一行都有最大值,所需的输出如下:

In [7]:
    frame.head()
    Out[7]:
    Communications and Search   Business    General Lifestyle   Max
    0   0.745763    0.050847    0.118644    0.084746           Communications 
    0   0.333333    0.000000    0.583333    0.083333           Business  
    0   0.617021    0.042553    0.297872    0.042553           Communications 
    0   0.435897    0.000000    0.410256    0.153846           Communications 
    0   0.358974    0.076923    0.410256    0.153846           Business 

Tags: and数据insearchbusinessoutframehead
3条回答

如果要生成一个列,其中包含具有最大值的列的名称,但只考虑列的子集,则可以使用@ajcr答案的变体:

df['Max'] = df[['Communications','Business']].idxmax(axis=1)

您可以在dataframe上apply,并通过axis=1获取每行的argmax()

In [144]: df.apply(lambda x: x.argmax(), axis=1)
Out[144]:
0    Communications
1          Business
2    Communications
3    Communications
4          Business
dtype: object

这里有一个基准来比较apply方法对于len(df) ~ 20K来说,idxmax()有多慢

In [146]: %timeit df.apply(lambda x: x.argmax(), axis=1)
1 loops, best of 3: 479 ms per loop

In [147]: %timeit df.idxmax(axis=1)
10 loops, best of 3: 47.3 ms per loop

您可以使用^{}axis=1来查找每行上具有最大值的列:

>>> df.idxmax(axis=1)
0    Communications
1          Business
2    Communications
3    Communications
4          Business
dtype: object

要创建新列“Max”,请使用df['Max'] = df.idxmax(axis=1)

要查找每个列中出现最大值的索引,请使用df.idxmax()(或等效的df.idxmax(axis=0))。

相关问题 更多 >