2

In a pandas dataframe, I want to replace nan values by a zero if values in an other column are not nan. I tried to adapt the answer from this question: pandas replace null values for a subset of columns

However, the nan values are not replaced (see code below). What did I do wrong? Thank you in advance.

df.loc[df['Litho'].notnull(),'Mu_alt'].fillna(0, inplace=True)
df.loc[df['Litho'].notnull(),'Mu_alt']
>>>0      NaN
>>>1      NaN
>>>2      NaN
>>>3      NaN
>>>4      NaN
>>>5      NaN
>>>6      NaN
>>>7      NaN

If I replace df['Litho'].notnull() by : in the first line, the nan values are replaced by a 0.

Antoine Caté
  • 107
  • 1
  • 8

1 Answers1

1

Assign back replaced values for avoid chained assignments:

m = df['Litho'].notnull()
df.loc[m,'Mu_alt'] = df.loc[m,'Mu_alt'].fillna(0)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • will there not be an easy way around like if `df.col2.notna` and col1 is na then simply zerp the col1 values, Just thinking loud :) – Karn Kumar Oct 26 '18 at 14:47