簡體   English   中英

熊貓:回填DataFrameGroupBy對象

[英]Pandas: Backfilling a DataFrameGroupBy object

我有一個看起來像這樣的DataFrame對象:

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

我想寫一些首先使用.groupby()函數按sensor分組的代碼。 然后回填每個組的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

因此,看起來res列上的ffill()起作用了,而pts列上的bfill()卻沒有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

我發現這個Stack Overflow鏈接問一個類似的問題,但是在一個DataFrame對象上,而不是一個DataFrameGroupBy對象上: 如何將pandas DataFrame值復制下來以填充0?

但是,當我嘗試在DataFrameGroupBy對象上執行DataFrameGroupBy ,它引發了一個錯誤: Cannot access callable attribute 'astype' of 'SeriesGroupBy' objects, try using the 'apply' method

任何幫助將不勝感激!

看起來它與groupby並沒有多大關系,而是與?fill函數有關,后者不會將int系列填充為0。

也許有一種更優雅的方式可以做到這一點,但這確實可行:

>> 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將float系列輕松轉換回int。

編輯第一行可以寫成

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM