【问题标题】:how can on define an operation over the most recent X days in a pandas frame?如何在熊猫框架中定义最近 X 天的操作?
【发布时间】:2020-09-18 13:10:32
【问题描述】:

假设我有一个带有服装连锁店销售数据的 pandas DataFrame:

model     day          shop   amount sold    price
polo      01-01-2006   B7     3              42.45
polo      01-01-2006   C8     4              41.45
polo      02-01-2006   C8     4              41.43
polo      03-01-2006   B8     1              41.45
sweater   01-01-2006   B7     2              71.57
sweater   02-01-2006   B7     2              71.56

我想计算过去 60 天内所有商店中每种型号的总收入。因此,对于上面的示例表,答案应该是 polo 包含时间序列的内容:

01-01-2006: 0
02-01-2006: 3*42.45 + 4*41.45
03-01-2006: 3*42.45 + 4*41.45 + 4*41.43

对于sweater 包含数据

01-01-2006: 0
02-01-2006: 2*71.57

该表很大(超过 10^8 行),因此首选计算效率高的答案。我可以灵活判断是过去 60 个日历日还是过去 60 天有任何可用数据,以最容易实施的为准。

我想我需要先按型号开始分组,然后按天分组,但不清楚如何在一定天数内创建滚动窗口,无论有多少商店有当天的数据行。或者,我考虑添加列start_dateend_date 以获得所需的时间间隔,但是不清楚如何告诉group_by 查询它应该总结这两者之间的所有日期。所以欢迎任何帮助

【问题讨论】:

  • 为什么您的示例显示 0 作为日期 01-01-2006 的结果?
  • @TobyPetty 因为前 60 天是 02-11-2005 到 31-12-2005,没有销售

标签: pandas


【解决方案1】:

试试这个:

# First, make sure that the `day` column is of type Timestamp, not string:
df['day'] = pd.to_datetime(df['day'])

# Add a revenue column
df['revenue'] = df['amount_sold'] * df['price']

# Sum revenue by model and day
# There is some index manipulation to prepare for the next command
tmp = df.groupby(['model', 'day'])['revenue'].sum().reset_index(level=0)

# For each model, calculate the previous 60 day revenue, excluding the ending day
# (hence closed on left but not right)
result = tmp.groupby('model').apply(lambda g: g.rolling('61D', closed='left').sum()).fillna(0)

结果:

                    revenue
model   day                
polo    2006-01-01     0.00
        2006-02-01   293.15
        2006-03-01   458.87
sweater 2006-01-01     0.00
        2006-02-01   143.14

【讨论】:

  • 实际上,几乎:结果框架似乎还没有model 列。有什么快速修复方法可以恢复吗? (比连接来自tmp 的列更好)
  • 此外,它似乎并没有真正起作用:第 0-59 天都显示滚动总和 0,而第 60 天(及以后)显示包含自身的总和
  • 已经发现它需要,min_periods=1 才能工作,但closed='right' 似乎什么也没做。可能需要简单地从中减去原始列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-12
相关资源
最近更新 更多