基于第一次出现的日期

问题描述 投票:1回答:1

我有一个pandas数据框的订单:

OrderID OrderDate   Value   CustomerID
1       2017-11-01  12.56   23
2       2017-11-06  1.56    23
3       2017-11-08  2.67    23
4       2017-11-12  5.67    99
5       2017-11-13  7.88    23
6       2017-11-19  3.78    99

让我们来看看ID为23的客户。他在历史上的第一个订单是2017-11-01。这个日期是他第一周的开始日期。这意味着他在2017-11-01和2017-11-07之间的所有订单都被分配到他的第1周(这不是像星期一到星期日那样的日历周)。对于ID为99的客户,第一周开始时为2017-11-12,因为这是他第一次订购的日期(OrderId 6)。

我需要将表的每个顺序分配给公共表Periods的相应索引。期间[0]将包含来自客户的第1周的订单,来自客户的第2周的期间[1]等等。订单1和订单1将与期货表的相同索引在两个订单在客户的第一周创建。

包含订单ID的周期表必须如下所示:Periods = [[1,2,4],[3,5,6]]

list pandas period
1个回答
0
投票

这是你想要的吗 ?

df['New']=df.groupby('CustomerID').OrderDate.apply(lambda x : (x-x.iloc[0]).dt.days//7)
df.groupby('New').OrderID.apply(list)
Out[1079]: 
New
0    [1, 2, 4]
1    [3, 5, 6]
Name: OrderID, dtype: object

获取您的期间表

df.groupby('New').OrderID.apply(list).tolist()
Out[1080]: [[1, 2, 4], [3, 5, 6]]

更多信息

df
Out[1081]: 
   OrderID  OrderDate  Value  CustomerID  New
0        1 2017-11-01  12.56          23    0
1        2 2017-11-06   1.56          23    0
2        3 2017-11-08   2.67          23    1
3        4 2017-11-12   5.67          99    0
4        5 2017-11-13   7.88          23    1
5        6 2017-11-19   3.78          99    1
© www.soinside.com 2019 - 2024. All rights reserved.