Pandas:回填DataFrameGroupBy对象

时间:2015-06-02 05:03:17

标签: python pandas

我有一个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

所以ffill()列上的res似乎有效,但bfill()列上的pts并没有效果。我如何让它看起来像这样?:

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对象: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

任何帮助都会非常感激!!

1 个答案:

答案 0 :(得分:0)

它看起来与groupby有很多关系,而不是?fill函数,它们不会用0填充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)