![](/img/trans.png)
[英]Best way to fill NaN values from multiple columns at the same time using specific columns of the same dataframe as reference
[英]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),则在轴 1 上选择 df 和 backword 填充的子集:
xdf['A']=xdf[['A','B','C']].bfill(1)['A']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.