如何将多列中的最大值返回到熊猫df中的新列

时间:2020-07-13 10:59:34

标签: python pandas

对不透明问题名称的道歉(不确定如何措词)。我有以下数据框:

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

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

2 个答案:

答案 0 :(得分:4)

DataFrame.idxmaxSeries.map一起使用,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

答案 1 :(得分:1)

@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