I need to impute the missing values of a categorical variable based on the values in second categorical variable using pandas dataframe

Viewed 83

Impute the missing values in first categorical variable(values- [0,1]) in such a way that if the values in second categorical variable(values- [1, 2, 3]) is either 2 or 3 then set the missing value in that row for first column to be 1 else set it to 0.

problem-

Col A Col B
0 1
1 2
NaN 3
NaN 2
NaN 1
0 1

Expected-

Col A Col B
0 1
1 2
1 3
1 2
0 1
0 1
1 Answers

Use Series.fillna for replace missing values by 1 if 2,3 tested by Series.isin and converted to integers for True, False to 1,0 mapping:

df['Col A'] = df['Col A'].fillna(df['Col B'].isin([2,3]).astype(int))
Related