使用以下数据帧“df”:
Customer_ID | Transaction_ID | Item_ID
ABC 2017-04-12-333 X8973
ABC 2017-04-12-333 X2468
ABC 2017-05-22-658 X2906
ABC 2017-05-22-757 X8790
ABC 2017-07-13-864 X8790
BCD 2017-08-11-879 X2346
BCD 2017-08-11-879 X2468
我想把客户的第一笔交易,第二笔交易,等等,按日期计算,列在指定的列中。(如果同一天有两笔交易,我把它们都算在同一笔账上,因为我没有时间,所以我不知道哪笔先到——基本上把它们当作一笔交易)。你知道吗
#get the date out of the Transaction_ID string
df['date'] = pd.to_datetime(df.Transaction_ID.str[:10])
#calculate the transaction number
df['trans_nr'] = df.groupby(['Customer_ID',"Transaction_ID", df['date'].dt.year]).cumcount()+1
不幸的是,这是我上面代码的输出:
Customer_ID | Transaction_ID | Item_ID | date | trans_nr
ABC 2017-04-12-333 X8973 2017-04-12 1
ABC 2017-04-12-333 X2468 2017-04-12 2
ABC 2017-05-22-658 X2906 2017-05-22 1
ABC 2017-05-22-757 X8790 2017-05-22 1
ABC 2017-07-13-864 X8790 2017-07-13 1
BCD 2017-08-11-879 X2346 2017-08-11 1
BCD 2017-08-11-879 X2468 2017-08-11 2
这是不正确的,这是我要找的正确输出:
Customer_ID | Transaction_ID | Item_ID | date | trans_nr
ABC 2017-04-12-333 X8973 2017-04-12 1
ABC 2017-04-12-333 X2468 2017-04-12 1
ABC 2017-05-22-658 X2906 2017-05-22 2
ABC 2017-05-22-757 X8790 2017-05-22 2
ABC 2017-07-13-864 X8790 2017-07-13 3
BCD 2017-08-11-879 X2346 2017-08-11 1
BCD 2017-08-11-879 X2468 2017-08-11 1
也许逻辑应该只基于客户ID和日期(没有交易ID)?你知道吗
我试过了
df['trans_nr'] = df.groupby(['Customer_ID','date').cumcount()+1
但它也算错了。你知道吗
一种方法是在进行累积计数之前删除重复值:
要获取事务号,首先删除具有重复
Customer_ID
和date
值的行。然后使用Customer_ID
和date
(稍后合并)设置它们的索引,并执行groupby
和cumcount
。这将生成一个系列,其值是每个Customer_ID
和date
的累积计数。你知道吗还可以为原始数据帧设置索引(同样允许合并)。然后您只需将
trans_nr
序列分配给df
中的一列。索引负责合并逻辑。你知道吗让我们试试:
输出:
将
dual groupby
与ngroup()
一起使用,即相关问题 更多 >
编程相关推荐