我有一个包含3列的pandas DataFrame:
a b c
0 1 1 10
1 2 12 10
2 16 13 10
3 9 16 10
在c
列中,我希望每行中最多包含3个数字,因此它应如下所示:
a b c
0 1 1 10
1 2 12 12
2 16 13 16
3 9 16 16
我可以使用for循环执行此操作,但我想知道是否有更简单的方法可以执行此操作?
答案 0 :(得分:6)
使用df.max(axis=1)
In [1807]: df['c'] = df.max(axis=1)
In [1808]: df
Out[1808]:
a b c
0 1 1 10
1 2 12 12
2 16 13 16
3 9 16 16
或者,assign
返回新数据框
In [1812]: df.assign(c=df.max(axis=1))
Out[1812]:
a b c
0 1 1 10
1 2 12 12
2 16 13 16
3 9 16 16