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.

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.