然后按日期过滤,得到平均值

2024-10-01 07:43:17 发布

您现在位置:Python中文网/ 问答频道 /正文

使用pandas dataframes,我试图根据CustId获取每行(不包括当前行本身)在过去90天内的平均购买数量,然后添加一个新列“PurchaseMeansLast90Days”

这是我尝试的代码,不正确:

group = df.groupby(['CustId'])
df['PurchaseMeanLast90Days'] = group.apply(lambda g: g[g['Date'] > (pd.DatetimeIndex(g['Date']) + pd.DateOffset(-90))])['Purchases'].mean()

以下是我的数据:

^{tb1}$

例如,行索引5将这些行包含在它的mean()=3.33中

^{tb2}$

新的数据帧将如下所示(我没有对CustId=2进行计算):

^{tb3}$

Tags: 数据代码pandasdf数量dategroupmean
1条回答
网友
1楼 · 发布于 2024-10-01 07:43:17

您可以执行滚动计算:

df["Date"] = pd.to_datetime(df["Date"], dayfirst=False)
df["PurchaseMeanLast90Days"] = (
    (
        df.groupby("CustId")
        .rolling("90D", min_periods=1, on="Date", closed="both")["Purchases"]
        .apply(lambda x: x.shift(1).sum() / (len(x) - 1))
    )
    .fillna(0)
    .values
)
print(df)

印刷品:

   Index  CustId       Date  Purchases  PurchaseMeanLast90Days
0      0       1 2021-01-01          5                0.000000
1      1       1 2021-01-12          1                5.000000
2      2       1 2021-03-28          2                3.000000
3      3       1 2021-04-01          4                2.666667
4      4       1 2021-04-20          2                3.000000
5      5       1 2021-05-01          5                2.666667
6      6       2 2021-01-01          1                0.000000
7      7       2 2021-02-01          1                1.000000
8      8       2 2021-03-01          2                1.000000
9      9       2 2021-04-01          3                1.333333

相关问题 更多 >