在Python3中为每个组创建日期序列

2024-10-03 02:39:30 发布

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

我有一个由多个商店/零售商组成的数据集:

RETAILER    VOLUME  DISP    PRICE
store1      12      15      10
store1      10      8       17
store1      12      13      12
...
store2      22      22      30
store2      17      14      22
store2      23      18      18
...
store3      11      13      10
store3      12      13      13
store3      14      12      11

不幸的是,这个数据集不包含日期,所以我需要为这个表中的每个存储生成日期序列。频率并不是很重要-几天或几个月就可以了

为了方便起见,我们假设它从2000-01-01开始,每个零售商的日期数取决于该零售商的观察次数

我可以在R中处理这个问题:

df <- df %>% 
  arrange(RETAILER) %>% 
  group_by(RETAILER) %>%  
  mutate(dates = seq(as.Date("2000-01-01"), by = "month", length.out = n()))

但是,我无法在Python中复制这一点。我一直在尝试pd.date\u range(),但找不到解决方案

有人能建议一些用Python执行此任务的方法吗

所需输出:

RETAILER    VOLUME  DISP    PRICE   DATE
store1      12      15      10      2000-01-01
store1      10      8       17      2000-02-01
store1      12      13      12      2000-03-01
...
store2      22      22      30      2000-01-01
store2      17      14      22      2000-02-01
store2      23      18      18      2000-03-01
...
store3      11      13      10      2000-01-01
store3      12      13      13      2000-02-01
store3      14      12      11      2000-03-01

Tags: 数据dfby序列次数price商店频率
1条回答
网友
1楼 · 发布于 2024-10-03 02:39:30

让我们groupRETAILER上创建数据帧,并使用cumcountRETAILER创建顺序计数器,然后map将此计数器添加到MonthBegin偏移量并添加Timestamp('2000-01-01')

c = df.groupby('RETAILER').cumcount()
df['DATE'] = pd.Timestamp('2000-01-01') + c.map(pd.offsets.MonthBegin)

  RETAILER  VOLUME  DISP  PRICE       DATE
0   store1      12    15     10 2000-01-01
1   store1      10     8     17 2000-02-01
2   store1      12    13     12 2000-03-01
3   store2      22    22     30 2000-01-01
4   store2      17    14     22 2000-02-01
5   store2      23    18     18 2000-03-01
6   store3      11    13     10 2000-01-01
7   store3      12    13     13 2000-02-01
8   store3      14    12     11 2000-03-01

相关问题 更多 >