我有一個DataFrame
對象,看起來像這樣:大熊貓:回填DataFrameGroupBy對象
Out[9]: pts res sensor
0 0 Y accel
1 0 NaN accel
2 0 N beta
3 0 NaN beta
4 5 NaN beta
5 8 NaN accel
我想編寫一個首先由sensor
使用.groupby()
功能將一些代碼。然後回填每個組的pts
列,並向前填充每個組的res
列。我的代碼的企圖看起來是這樣的:
df_g = df.groupby('sensor')
next_pts = pd.Series(df_g.pts.bfill())
next_res = pd.Series(df_g.res.ffill())
df['next_pts'] = next_pts
df['next_res'] = next_res
df
輸出是這樣的:
Out[11]: pts res sensor next_pts next_res
0 0 Y accel 0 Y
1 0 NaN accel 0 Y
2 0 N beta 0 N
3 0 NaN beta 0 N
4 5 NaN beta 5 N
5 8 NaN accel 8 Y
所以看起來像ffill()
在res
列的工作,但對pts
列bfill()
沒有。我如何使它看起來像這樣?:
Out[12]: pts res sensor next_pts next_res
0 0 Y accel 8 Y
1 0 NaN accel 8 Y
2 0 N beta 5 N
3 0 NaN beta 5 N
4 5 NaN beta 5 N
5 8 NaN accel 8 Y
我發現,問過類似的問題這個堆棧溢出鏈接,但在DataFrame
對象,而不是DataFrameGroupBy
對象:How to copy pandas DataFrame values down to fill 0's?
但是,當我試圖做像這樣在我的DataFrameGroupBy
對象上,它拋出了一個錯誤:Cannot access callable attribute 'astype' of 'SeriesGroupBy' objects, try using the 'apply' method
任何幫助將非常感謝!
'ffill'和'bfill'替換'NaN'值不爲0值,這是由設計,你必須更換你的'0爲了達到您想要的結果,使用'NaN'值設置''值 – EdChum