Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将多个列中的最高值返回到数据集中的新列_Python_Pandas - Fatal编程技术网

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

Python 如何将多个列中的最高值返回到数据集中的新列,python,pandas,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,

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

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

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

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

New Col
Carrot
Apple
Banana
Carrot
任何帮助都将不胜感激!谢谢

沿
轴=1使用

结果:

  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

@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

这太棒了-非常感谢!(如果可以,我会接受答案)如果没有唯一的最大值怎么办?通常没有唯一的答案(值浮动到3位小数),但在平局的情况下,两个值中的任何一个都可以
    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