2015-06-02 45 views
0

我有一個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列的工作,但對ptsbfill()沒有。我如何使它看起來像這樣?:

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

任何幫助將非常感謝!

+0

'ffill'和'bfill'替換'NaN'值不爲0值,這是由設計,你必須更換你的'0爲了達到您想要的結果,使用'NaN'值設置''值 – EdChum

回答

0

它看起來不像groupby,而是?fill函數,它們不會用int填充int系列。

也許還有一個更優雅的方式做到這一點,但這個工作:

>> df.pts = np.where(df.pts == 0, np.NaN, df.pts) 
>> df.pts.groupby(df.sensor).apply(lambda g: g.bfill()) 
0 8 
1 8 
2 5 
3 5 
4 5 
5 8 
dtype: float64 

注意,您可以浮動系列轉換回整數輕鬆使用.astype

編輯第一行可以寫成

>> df.pts.replace(0, np.NaN)