gpt4 book ai didi

Python Pandas为选定列的逐行最大值添加列

转载 作者:IT老高 更新时间:2023-10-28 21:37:03 33 4
gpt4 key购买 nike

data = {'name' : ['bill', 'joe', 'steve'],
'test1' : [85, 75, 85],
'test2' : [35, 45, 83],
'test3' : [51, 61, 45]}
frame = pd.DataFrame(data)

我想添加一个显示每行最大值的新列。

想要的输出:

 name test1 test2 test3 HighScore
bill 75 75 85 85
joe 35 45 83 83
steve 51 61 45 61

有时

frame['HighScore'] = max(data['test1'], data['test2'], data['test3'])

有效,但大多数时候会出现此错误:

ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

为什么它有时只起作用?还有其他方法吗?

最佳答案

>>> frame['HighScore'] = frame[['test1','test2','test3']].max(axis=1)
>>> frame
name test1 test2 test3 HighScore
0 bill 85 35 51 85
1 joe 75 45 61 75
2 steve 85 83 45 85

关于Python Pandas为选定列的逐行最大值添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20033111/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com