如何将多个列中的最高值返回到数据集中的新列

2024-09-29 08:17:02 发布

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

为不透明的问题名称道歉(不知道如何用词)。我有以下数据帧:

import pandas as pd
import numpy as np

data = [['tom', 1,1,6,4],
        ['tom', 1,2,2,3],
        ['tom', 1,2,3,1],
        ['tom', 2,3,2,7],
        ['jim', 1,4,3,6],
        ['jim', 2,6,5,3]]

df = pd.DataFrame(data, columns = ['Name', 'Day','A','B','C']) 
df = df.groupby(by=['Name','Day']).agg('sum').reset_index()
df

enter image description here

我想添加另一个返回文本的列,根据A,B,C的哪一列是最高的:

例如,我想要Apple如果A是最高的,Banana如果B是最高的,Carrot如果C是最高的。因此,在上述示例中,4列的值应为:

New Col
Carrot
Apple
Banana
Carrot

任何帮助都将不胜感激!谢谢


Tags: 数据nameimport名称appledfdataas
2条回答

@ShubhamSharma的答案比这更好,但这里有另一个选择:

df['New col'] = np.where((df['A'] > df['B']) & (df['A'] > df['C']), 'Apple', 'Carrot')
df['New col'] = np.where((df['B'] > df['A']) & (df['B'] > df['C']), 'Banana', df['New col'])

输出:

    Name    Day A   B   C   New col
0   jim 1   4   3   6   Carrot
1   jim 2   6   5   3   Apple
2   tom 1   5   11  8   Banana
3   tom 2   3   2   7   Carrot

使用^{}沿axis=1^{}连用:

dct = {'A': 'Apple', 'B': 'Banana', 'C': 'Carrot'}
df['New col'] = df[['A', 'B', 'C']].idxmax(axis=1).map(dct)

结果:

  Name  Day  A   B  C New col
0  jim    1  4   3  6  Carrot
1  jim    2  6   5  3   Apple
2  tom    1  5  11  8  Banana
3  tom    2  3   2  7  Carrot

相关问题 更多 >