![](/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.