python - 将函数应用于 Pandas Groupby

标签 python pandas apply moving-average pandas-groupby

我目前正在使用 Python 处理面板数据,并尝试计算给定组 (ID) 内每个时间序列观察的滚动平均值。

考虑到我的数据集的大小(数千个具有多个时间段的组),.groupby 和 .apply() 函数的计算时间太长(已经运行了一个多小时,但仍然没有任何数据 - 整个数据)集合仅包含大约 300k 个观察值)。

我最终想要迭代多个列,执行以下操作:

  1. 计算每个组 ID 给定列中每个时间步长的滚动平均值
  2. 创建一个新列,其中包含原始值与移动平均值之间的差值 [x_t - (x_t-1 + x_t)/2]
  3. 将列存储在新的 DataFrame 中,该新 DataFrame 与原始数据集相同,只是它具有 #2 的残差而不是原始值。
  4. 重复并将新残差附加到 df_resid(如下所示)

    df_resid
    date        id   rev_resid   exp_resid
    2005-09-01   1         NaN         NaN
    2005-12-01   1      -10000       -5500
    2006-03-01   1     -352584   -262058.5
    2006-06-01   1      240000    190049.5 
    2006-09-01   1    82648.75    37724.25
    2005-09-01   2         NaN         NaN
    2005-12-01   2      4206.5       24353
    2006-03-01   2     -302574     -331951
    2006-06-01   2      103179    117405.5
    2006-09-01   2      -52650    -72296.5
    

这是原始数据的小样本。

df
date        id        rev        exp
2005-09-01   1   745168.0   545168.0    
2005-12-01   1   725168.0   534168.0    
2006-03-01   1    20000.0    10051.0
2006-06-01   1   500000.0   390150.0
2006-09-01   1   665297.5   465598.5
2005-09-01   2   956884.0   736987.0
2005-12-01   2   965297.0   785693.0
2006-03-01   2   360149.0   121791.0
2006-06-01   2   566507.0   356602.0
2006-09-01   2   461207.0   212009.0

以及(非常慢的)代码:

df['rev_resid'] = df.groupby('id')['rev'].apply(lambda x:x.rolling(center=False,window=2).mean()) 

我希望有一种计算效率更高的方法来做到这一点(主要是关于#1),并且可以扩展到多列。

任何帮助将不胜感激。

最佳答案

为了加快计算速度,如果数据帧已经按 'id' 排序,那么您不必在 groupby 中进行滚动 > (如果未排序...则这样做)。然后,由于您的窗口长度仅为 2,因此我们通过检查 id == id.shift 的位置来屏蔽结果。这之所以有效,是因为它已排序。

d1 = df[['rev', 'exp']]
df.join(
    d1.rolling(2).mean().rsub(d1).add_suffix('_resid')[df.id.eq(df.id.shift())]
)

         date  id       rev       exp  rev_resid  exp_resid
0  2005-09-01   1  745168.0  545168.0        NaN        NaN
1  2005-12-01   1  725168.0  534168.0  -10000.00   -5500.00
2  2006-03-01   1   20000.0   10051.0 -352584.00 -262058.50
3  2006-06-01   1  500000.0  390150.0  240000.00  190049.50
4  2006-09-01   1  665297.5  465598.5   82648.75   37724.25
5  2005-09-01   2  956884.0  736987.0        NaN        NaN
6  2005-12-01   2  965297.0  785693.0    4206.50   24353.00
7  2006-03-01   2  360149.0  121791.0 -302574.00 -331951.00
8  2006-06-01   2  566507.0  356602.0  103179.00  117405.50
9  2006-09-01   2  461207.0  212009.0  -52650.00  -72296.50

关于python - 将函数应用于 Pandas Groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45493556/

相关文章:

python - 在 scikit learn 中使用标签编码器编码数据时出现类型错误

python - 创建与另一个尺寸相同的空数据框?

python - Pandas自条件列

python - 当数据库是第二个位置参数时,Pandas 应用函数

r - 检查是否有任何值在范围内

python - django send_mail 554 - 中继访问被拒绝

内置服务器的python不加载css

r - 在检查 data.frame 中的列类时 apply() 不起作用

Python 2.7.9 Mac OS 10.10.3 消息 "setCanCycle: is deprecated. Please use setCollectionBehavior instead"

python - pandas 系列中的部分字符串替换