Replacing null values with multiple values using different conditions in python

Question:

The dataset contains 1581 rows and 14 columns. Dataset is loaded as df.
Important columns for this problem are Partner_working (values: Yes, No) and Partner_salary.

There are 106 null values in Partner_salary column. I have to replace these null values with the median value of Partner_salary if Partner_working is Yes and if the Partner_working is No I have to replace the null value with 0.

I am having the problem with code. I have to use for loop and if else condition inside it. Please help with the code.

Asked By: Neha

||

Answers:

You can create two fillna and then concat them:

med =  df[df.Partner_working == 'Yes'].Partner_salary.fillna(df.Partner_salary.median())
zeros = df[df.Partner_working == 'No'].Partner_salary.fillna(0)
df.Partner_salary = pd.concat([med, zeros]).sort_index()
Answered By: Nuri Taş