找到每行具有最大值的列名

问题描述 投票:0回答:5

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

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

我想创建一个由每行最大值的列标签组成的新列。期望的输出是这样的:

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 
python pandas dataframe max argmax
5个回答
298
投票

您可以使用

idxmax
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)

要查找每列中出现最大值的 row 索引,请使用

df.idxmax()
(或等效的
df.idxmax(axis=0)
)。


54
投票

如果您想生成一个包含具有最大值的列名称的列,但仅考虑列的子集,那么您可以使用 @ajcr 答案的变体:

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

14
投票

您可以在数据帧上

apply
并通过
argmax()
 获取每行的 
axis=1

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
方法与
idxmax()
对于
len(df) ~ 20K

的速度有多慢
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

6
投票

另一种解决方案是标记每行最大值的位置并获取相应的列名称。特别是,如果多个列包含某些行的最大值并且您希望为每行返回具有最大值的所有列名称,则此解决方案效果很好:1

代码:

# look for the max values in each row
mxs = df.eq(df.max(axis=1), axis=0)
# join the column names of the max values of each row into a single string
df['Max'] = mxs.dot(mxs.columns + ', ').str.rstrip(', ')

略有不同:如果您想在多列包含最大值时随机选择一列::

代码:

mxs = df.eq(df.max(axis=1), axis=0) df['Max'] = mxs.where(mxs).stack().groupby(level=0).sample(n=1).index.get_level_values(1)


您还可以通过选择列来对特定列执行此操作:

# for column names of max value of each row cols = ['Communications', 'Search', 'Business'] mxs = df[cols].eq(df[cols].max(axis=1), axis=0) df['max among cols'] = mxs.dot(mxs.columns + ', ').str.rstrip(', ')


1:如果多列的最大值相同,则idxmax(1)

仅返回具有最大值的第一个列名称,根据用例,这可能并不理想。该解决方案概括了 
idxmax(1)
;特别是,如果每行中的最大值都是唯一的,则它与 
idxmax(1)
 解决方案匹配。


1
投票
使用 numpy argmax 速度非常快。我在包含 3,744,965 行的数据帧中进行了测试,需要 103 毫秒。

%timeit df.idxmax(axis=1) 7.67 s ± 28.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit df.columns[df.to_numpy().argmax(axis=1)] 103 ms ± 355 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
© www.soinside.com 2019 - 2024. All rights reserved.