Answers for "mask and then fillna"

0

mask and then fillna

a b c 
1 1 5.0
1 1 None
1 1 4.0
1 2 1.0
1 2 1.0
1 2 4.0 
2 1 3.0
2 1 2.0
2 1 None
2 2 3.0
2 2 4.0

mask = (df['a']==1) & (df['b']==1)
mean = df.loc[mask, 'c'].mean()
df.loc[mask, 'c'] = df.loc[mask, 'c'].fillna(mean)

df['c'] = df['c'].mask(mask, df['c'].fillna(mean))
#similar
#df['c'] = np.where(mask, df['c'].fillna(mean), df['c'])

print (df)
    a  b    c
0   1  1  5.0
1   1  1  4.5
2   1  1  4.0
3   1  2  1.0
4   1  2  1.0
5   1  2  4.0
6   2  1  3.0
7   2  1  2.0
8   2  1  NaN
9   2  2  3.0
10  2  2  4.0
Posted by: Guest on March-20-2021

Python Answers by Framework

Browse Popular Code Answers by Language