Python - 时间序列对齐和 "to date"函数

标签 python date alignment pandas time-series

我有一个包含以下前三列的数据集。 包括购物篮 ID(唯一标识符)、销售额(美元)和交易日期。我想为数据集的每一行计算以下列,我想在 Python 中进行。

同一篮子的

先前销售(如果有);当前购物篮的销售数量;当前篮子的均值(如果可用);当前篮子的最大截止日期(如果可用)

Basket  Sale   Date       PrevSale SaleCount MeanToDate MaxToDate
88      $15 3/01/2012                1      
88      $30 11/02/2012      $15      2         $23        $30
88      $16 16/08/2012      $30      3         $20        $30
123     $90 18/06/2012               1      
477     $77 19/08/2012               1      
477     $57 11/12/2012      $77      2         $67        $77
566     $90 6/07/2012                1      

我是 Python 的新手,我真的很难找到任何可以用奇特的方式来做的东西。我已经按 BasketID 和日期对数据(如上所述)进行了排序,因此我可以通过为每个篮子向前移动一个来批量获取之前的销售。除了循环之外,不知道如何以有效的方式获取 MeanToDate 和 MaxToDate ...有什么想法吗?

最佳答案

这应该可以解决问题:

from pandas import concat
from pandas.stats.moments import expanding_mean, expanding_count

def handler(grouped):
    se = grouped.set_index('Date')['Sale'].sort_index()
    # se is the (ordered) time series of sales restricted to a single basket
    # we can now create a dataframe by combining different metrics
    # pandas has a function for each of the ones you are interested in!
    return  concat(
        {
            'MeanToDate': expanding_mean(se), # cumulative mean
            'MaxToDate': se.cummax(),         # cumulative max
            'SaleCount': expanding_count(se), # cumulative count
            'Sale': se,                       # simple copy
            'PrevSale': se.shift(1)           # previous sale
        },
        axis=1
     )

# we then apply this handler to all the groups and pandas combines them
# back into a single dataframe indexed by (Basket, Date)
# we simply need to reset the index to get the shape you mention in your question
new_df = df.groupby('Basket').apply(handler).reset_index()

您可以阅读更多关于分组/聚合的信息 here .

关于Python - 时间序列对齐和 "to date"函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15489011/

相关文章:

python - TensorFlow:如何命名 tf.get_variable 的操作

python - 为什么这个 Keras python 程序失败了?

c - 输入错误后循环返回,fgetc(stdin) 问题和循环

arrays - Swift - 在一个大的时间范围内按一年中的一周对一系列项目进行分组

c# - 应用程序查询时 Azure 移动服务字符串/日期列出现问题

android - 在水平线性布局内对齐按钮

python - 在普通代码中使用断言

python - 反转 'password_change_done',参数 '()' 和关键字参数 '{}' 未找到。 0 种模式已尝试 : []

python - Python 的 Tabulate 逗号对齐错误

html - 使用显示内联 block 在 div 中输入文本时对齐方式发生变化