Reputation: 625
I have the following data frame
import pandas as pd
import numpy as np
d = {
'ID':[1,2,3],
'W1':[5,6,7],
'W2':[9, np.nan,10],
'w3':[11,np.nan,np.nan]
}
df = pd.DataFrame(data = d)
df
ID W1 W2 w3
0 1 5 9.0 11.0
1 2 6 NaN NaN
2 3 7 10.0 NaN
I am doing the following operations
df['Sum1'] = (df[['W1','W2']]).sum(axis = 1)/2
df['Sum2'] = (df[['W2','w3']]).sum(axis = 1)/2
ID W1 W2 w3 Sum1 Sum2
0 1 5 9.0 11.0 7.0 10.0
1 2 6 NaN NaN 3.0 0.0
2 3 7 10.0 NaN 8.5 5.0
How to make Sum2 of ID "2" as NaN instead of 0 after doing the above operations??
Upvotes: 1
Views: 203
Reputation: 862761
Add parameter min_count=1
to DataFrame.sum
:
min_count : int, default 0
The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.New in version 0.22.0: Added with the default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1.
df['Sum1'] = (df[['W1','W2']]).sum(axis = 1, min_count=1)/2
df['Sum2'] = (df[['W2','w3']]).sum(axis = 1, min_count=1)/2
print (df)
ID W1 W2 w3 Sum1 Sum2
0 1 5 9.0 11.0 7.0 10.0
1 2 6 NaN NaN 3.0 NaN
2 3 7 10.0 NaN 8.5 5.0
But is seems you need mean
s - then it working like need:
df['Sum1'] = (df[['W1','W2']]).mean(axis = 1)
df['Sum2'] = (df[['W2','w3']]).mean(axis = 1)
print (df)
ID W1 W2 w3 Sum1 Sum2
0 1 5 9.0 11.0 7.0 10.0
1 2 6 NaN NaN 6.0 NaN
2 3 7 10.0 NaN 8.5 10.0
Upvotes: 2