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

我有一个这样的数据帧:

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
144178 次浏览

您可以在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方法与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

您可以使用idxmaxaxis=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))。

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

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

另一种解决方案是标记每行的最大值的位置,并获取相应的列名。特别是,如果Max值在多个列中都相同,并且您希望为每一行返回具有最大值的所有列名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
df['Max'] = mxs.dot(mxs.columns + ', ').str.rstrip(', ')

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

# 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)解决方案匹配。

使用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)