Python Dataframe 从多列中填充 nan

Python Dataframe fill nan from multiple columns

我有一个包含 3 列的数据框。我想在第一列中用第二列填充nan。如果第二列也有nan,则转到第三列

我的代码:

xdf = pd.DataFrame({'A':[10,20,np.nan,np.nan],'B':[15,np.nan,30,np.nan],'C':[np.nan,np.nan,35,40]})

# fill nan in A
xdf['A'].fillna(xdf[['B','C']],inplace=True)

当前输出:

TypeError: "value" parameter must be a scalar, dict or Series, but you passed a "DataFrame"

预期输出:

xdf = 
      A     B     C
0  10.0  15.0   NaN
1  20.0   NaN   NaN
2  30.0  30.0  35.0
3  40.0   NaN  40.0

尝试通过 bfill():

xdf['A']=xdf.bfill(1)['A']

df的输出:

    A       B       C
0   10.0    15.0    NaN
1   20.0    NaN     NaN
2   30.0    30.0    35.0
3   40.0    NaN     40.0

更新:

如果有额外的列(如 D、E)不需要填充,那么 select df 的子集和轴 1 上的反向词填充:

xdf['A']=xdf[['A','B','C']].bfill(1)['A']