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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.