Home > Net >  Impute column based on another column is NaN or not
Impute column based on another column is NaN or not

Time:01-11

I have a simple df here. So basically for Null values in ["A"] if the same row has no null value for ["B"] then make the ["A"] equal to ["B"] and if they are both null then it should just skip.

Code:

test = {'A': [3, np.nan, np.nan, 0], 'B': [4, 5, np.nan, 10]}

test_df = pd.DataFrame.from_dict(test)

test_df

##EXPECTED OUTPUT:

output = test = {'A': [3, 5, np.nan, 0], 'B': [4, 5, np.nan, 10]}

output_df= pd.DataFrame.from_dict(test)

output_df

I tried solving this through using lambda function using & condition but it looks too messy and inefficient to me. I was wondering if there is a simple clean way of doing this.

CodePudding user response:

fillnaing a Series with another Series does exactly what you describe:

In [304]: test_df["A"] = test_df["A"].fillna(test_df["B"])

In [305]: test_df
Out[305]:
     A     B
0  3.0   4.0
1  5.0   5.0
2  NaN   NaN
3  0.0  10.0
  • Related