![](/img/trans.png)
[英]Pandas: Sum multiple columns, but write NaN if any column in that row is NaN or 0
[英]Pandas - append column with sum of row values (if sum is even), or NaN (if odd)
我有一个数据框,我想要一个新列t
其中包含同一行中其他列的总和。 标准是如果总和是奇数,我想要NaN
如果值是偶数,我想要NaN
。
df = pd.DataFrame([[1, 8, 7, 2],
[8, 5, 9, 4],
[1, -5, 3, -2]], columns=list('pqrs'))
df
p q r s
0 1 8 7 2
1 8 5 9 4
2 1 -5 3 -2
Expected output:
p q r s t
0 1 8 7 2 18.0
1 8 5 9 4 26.0
2 1 -5 3 -2 NaN
使用np.where
:
df['new'] = np.where(df.sum(1)%2==0, df.sum(1), np.nan)
df
p q r s new
0 1 8 7 2 18.0
1 8 5 9 4 26.0
2 1 -5 3 -2 NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.