[英]Python Dataframe fill nan from multiple columns
I have a data frame with 3 columns.我有一个包含 3 列的数据框。 I want to fill
nan
in the first column with the second column.我想用第二列填充第一列中的
nan
。 If there is also nan
in the second, go to the third column.如果第二列中也有
nan
,则转到第三列。
My code:我的代码:
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)
Present output:当前输出:
TypeError: "value" parameter must be a scalar, dict or Series, but you passed a "DataFrame"
Expected output:预期输出:
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
Try via bfill()
:通过
bfill()
尝试:
xdf['A']=xdf.bfill(1)['A']
output of df
: 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
Update:更新:
if there were additional columns (like D, E) not needed to fillna then select the subset of df and backword fill on axis 1:如果不需要填充其他列(如 D、E),则在轴 1 上选择 df 和 backword 填充的子集:
xdf['A']=xdf[['A','B','C']].bfill(1)['A']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.