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


122

我有一个像这样的DataFrame:

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 

Answers:


164

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


@SushantKulkarni您如何设法获得前三位的概率而不是前三位的概率?
Stergios

#计算所有accountsproba = lr.predict_proba(TFIDF)MLR_y_p = pd.DataFrame概率(PROBA,列= np.unique(y)时,索引= df.Key.tolist())
Sushant库尔卡尼

25

如果要生成包含最大值的列名但仅考虑列子集的列,则可以使用@ajcr答案的变体:

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

5
如果要排除除了一个子集中的所有列df['Max'] = df[df.columns.difference(['Foo','Bar'])].idxmax(axis=1)
floatingpurr

9

您可以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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.