【问题标题】:Find the column name which has the maximum value for each row查找每行具有最大值的列名
【发布时间】:2015-07-07 07:07:48
【问题描述】:

我有一个像这样的 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 

【问题讨论】:

    标签: python pandas dataframe max


    【解决方案1】:

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

    【讨论】:

    • @SushantKulkarni 你是如何设法获得前 3 名而不是前 1 名的概率?
    • #计算所有账户的概率proba = lr.predict_proba(tfidf) MLR_y_p = pd.DataFrame(proba, columns=np.unique(y), index=df.Key.tolist())跨度>
    • 这只是一个问题:如果列中的值相同,则 idmax 选择第一列作为默认值...不理想..
    • 只是不要将该列命名为“第一”。没有抛出错误,一切正常,包括显示数据框时,但 'first' 是保留关键字。当您开始操作数据框时,它稍后会引发错误
    • 有没有办法以与第一个相同的方式获得第二个和第三个最大值?
    【解决方案2】:

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

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

    【讨论】:

    • 如果要排除除子集df['Max'] = df[df.columns.difference(['Foo','Bar'])].idxmax(axis=1)之外的所有列@
    【解决方案3】:

    您可以在数据帧上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
    

    【讨论】:

    • 我喜欢这种方法。它似乎比apply 快。有没有机会我只能对此进行小幅调整以获得具有第二大值的列名?谢谢。
    猜你喜欢
    • 2021-05-06
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多