Pandas - 用行值的总和(如果总和是偶数)或 NaN(如果是奇数)追加列 [英] Pandas - append column with sum of row values (if sum is even), or NaN (if odd)
本文介绍了Pandas - 用行值的总和(如果总和是偶数)或 NaN(如果是奇数)追加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,我想要一个新列 t
与同一行中其他列的总和.标准是如果总和是奇数,我想要 NaN
,如果值是偶数,我想要总和.
I have a dataframe and I want a new column t
with sum of other columns in the same row. Criteria is I want NaN
if the sum is odd, and the sum if the value is even.
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
推荐答案
Using 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
这篇关于Pandas - 用行值的总和(如果总和是偶数)或 NaN(如果是奇数)追加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文