如何在这个 MultiIndex 数据帧中计算 pandas 的滚动窗口总和?

数据挖掘 Python 熊猫
2021-09-28 17:38:02

我不知道如何从这些数据中获得移动的年度总和:

>                          revenue
> txdate   2014-01-31     2014-02-28      2014-03-31     2014-04-30     ....
> user_id
> 1            0              10             165             0
> 2          265             265             200           250
> 3          770             985            1235           900
> ....

以前我会尝试这样的事情并进行调整,直到它起作用:

df.groupby(level='practice_id').apply(lambda x: pd.rolling_sum(x, 12))

但它已被弃用,尽管阅读了文档,但我并没有理解 0.18 对滚动的更改,而且我不确定数据的形状是否有帮助(它接近需要插入到 db 表中的内容) . 原始数据格式如下:

> txdate          user_id        tx_amount
> 2014-01-01         2               5
> 2014-01-02         2               5
> 2014-01-02         3              30
> 2014-01-03         3              15
> 2014-01-02         2              10

我用以下 cmd 重塑:

> df.set_index('txdate').groupby('user_id').resample('M').agg({'revenue': np.sum})

我想我可能需要颠倒操作顺序。

1个回答

如果其他人来看,这是我的解决方案:

# find last column
last_column = df.shape[1]-1

# grab the previous 11 columns (also works if there aren't that many in the df)
wanted = df.iloc[:, (last_column-11):last_column]

# calculate the rounded moving annual total 
mat_calc = round(wanted.sum(axis=1)/len(wanted.columns), 2)

可能不是最流行的解决方案,但效果很好。