Antoine Caté
Antoine Caté

Reputation: 107

pandas replace null values for a subset of rows and columns

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.

Upvotes: 2

Views: 1690

Answers (1)

jezrael
jezrael

Reputation: 862661

Assign back replaced values for avoid chained assignments:

m = df['Litho'].notnull()
df.loc[m,'Mu_alt'] = df.loc[m,'Mu_alt'].fillna(0)

Upvotes: 1

Related Questions