This is my DataFrame:
import pandas as pdimport numpy as npdf = pd.DataFrame( {'x': [1, np.nan, 3, np.nan, 5],'y': [np.nan, 7, 8, 9, np.nan],'x_a': [1, 2, 3, 4, 5],'y_a': [6, 7, 8, 9, 10] })
Expected output is fill_na
columns x
and y
:
x y x_a y_a0 1.0 6.0 1 61 2.0 7.0 2 72 3.0 8.0 3 83 4.0 9.0 4 94 5.0 10.0 5 10
Basically I want to fillna x
with x_a
and y
with y_a
. In other words each column should be paired with another column that has the suffix _a
and the column name.
I can get this output by using this code:
for col in ['x', 'y']: df[col] = df[col].fillna(df[f'{col}_a'])
But I wonder if it is the best/most efficient way? Suppose I got hundreds of columns like these