基于首次出现的日期期间
Date periods based on first occurence
我有一个 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) 的日期。
我需要将 table 的每个订单分配给公共 table 期间的相应索引。 Periods[0] 将包含来自客户第 1 周的订单,Periods[1] 来自客户第 2 周等。
OrderId 1 nad OrderId 6 将在相同的周期索引中 table,因为这两个订单都是在其客户的第一周创建的。
table 期间包含的订单 ID 必须如下所示:
周期=[[1,2,4],[3,5,6]]
这是你想要的吗?
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
来月经table
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
我有一个 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) 的日期。
我需要将 table 的每个订单分配给公共 table 期间的相应索引。 Periods[0] 将包含来自客户第 1 周的订单,Periods[1] 来自客户第 2 周等。 OrderId 1 nad OrderId 6 将在相同的周期索引中 table,因为这两个订单都是在其客户的第一周创建的。
table 期间包含的订单 ID 必须如下所示: 周期=[[1,2,4],[3,5,6]]
这是你想要的吗?
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
来月经table
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