Pandas - append column with sum of row values (if sum is even), or NaN (if odd)

让人想犯罪 __ 提交于 2021-01-27 16:42:43

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/53512640/pandas-append-column-with-sum-of-row-values-if-sum-is-even-or-nan-if-odd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!