Pandas : fill values from from another column

Viewed 42

I did a pandas merge and now have two columns - col_x and col_y. I'd like to fill values in col_x with col_y, but only for rows where where col_y is not NaN or has a value. I'd like to keep the original values in col_x and only replace from col_y if NaN.

import pandas as pd

df = pd.DataFrame({
                   'i': [0, 1, 2, 3],
                   'c': [np.nan, {'a':'A'}, np.nan, {'b':'B'}],
                   'd': [{'c':'C'}, np.nan, {'d':'D'}, np.nan]
                 })

Expected output:

i    c         d
0  {'c':'C'}   {'c':'C'}      
1  {'a':'A'}   np.nan
2  {'d':'D'}   {'d':'D'}
3  {'b':'B'}   np.nan
3 Answers

Are you just trying to fillna?

df.c.fillna(df.d, inplace=True)

You can use np.where()

So something like

df['c'] = np.where(df['c'].isna(), df['d'], df['c'])

should do the trick! The first parameter is the condition to check, the second is what to return if the condition is true, and the third is what to return if the condition is false.

Try:

df["c"] = [y if str(x) == "nan" else x for x,y in zip(df.c,df.d)]

Probably cleaner way but this is one line

Related