简体   繁体   中英

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.

Assign back replaced values for avoid chained assignments :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM