3

Am trying to do a fillna with if condition

Fimport pandas as pd
df = pd.DataFrame(data={'a':[1,None,3,None],'b':[4,None,None,None]})
print df

df[b].fillna(value=0, inplace=True) only if df[a] is None
print df


  a   b
0 1   4
1 NaN NaN
2 3   NaN
3 NaN NaN

##What i want to acheive

  a   b
0 1   4
1 NaN 0
2 3   NaN
3 NaN 0

Please help

ravijprs
  • 39
  • 1
  • 4

1 Answers1

2

You can chain both conditions for test mising values with & for bitwise AND and then replace values to 0:

df.loc[df.a.isna() & df.b.isna(), 'b'] = 0
#alternative
df.loc[df[['a', 'b']].isna().all(axis=1), 'b'] = 0
print (df)
     a    b
0  1.0  4.0
1  NaN  0.0
2  3.0  NaN
3  NaN  0.0

Or you can use fillna with one condition:

df.loc[df.a.isna(), 'b'] = df.b.fillna(0)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252