Python Pandas 为所选列的行列最大值添加列 [英] Python Pandas add column for row-wise max value of selected columns

查看:46
本文介绍了Python Pandas 为所选列的行列最大值添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I would like to add a new column that shows the max value for each row.

期望的输出:

 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'])

有效,但大多数情况下会出现此错误:

works but most of the time gives this error:

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

为什么它只是有时有效?还有其他方法吗?

Why does it only work sometimes? Is there another way of doing it?

推荐答案

>>> 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 为所选列的行列最大值添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆