我想创建一个列,以显示在部门99进行的先前购买(每个客户)的累计计数(滚动总和)
我的数据框看起来像这样;每行是一个单独的事务。
id chain dept category company brand date productsize productmeasure purchasequantity purchaseamount sale
0 86246 205 7 707 1078778070 12564 2012-03-02 12.00 OZ 1 7.59 268.90
1 86246 205 63 6319 107654575 17876 2012-03-02 64.00 OZ 1 1.59 268.90
2 86246 205 97 9753 1022027929 0 2012-03-02 1.00 CT 1 5.99 268.90
3 86246 205 25 2509 107996777 31373 2012-03-02 16.00 OZ 1 1.99 268.90
4 86246 205 55 5555 107684070 32094 2012-03-02 16.00 OZ 2 10.38 268.90
5 86246 205 97 9753 1021015020 0 2012-03-02 1.00 CT 1 7.80 268.90
6 86246 205 99 9909 104538848 15343 2012-03-02 16.00 OZ 1 2.49 268.90
7 86246 205 59 5907 102900020 2012 2012-03-02 16.00 OZ 1 1.39 268.90
8 86246 205 9 921 101128414 9209 2012-03-02 4.00 OZ 2 1.50 268.90
我这样做了:
shopdata6['transactions_99'] = 0
shopdata6['transactions_99'] = shopdata6[shopdata6['dept'] == 99].groupby(['id', 'dept'])['transaction_99'].cumsum()
更新:
id dept date purchase purchase_count_dept99(desired)
id1 199 date1 $10 0
id1 99 date1 $10 1
id1 100 date1 $50 1
id1 99 date2 $30 2
id2 100 date1 $10 0
id2 99 date1 $10 1
id3 99 date3 $10 1
应用了此:
shopdata6['transaction_99'] = np.where(shopdata6['dept']==99, 1, 0)
shopdata6['transaction_99'] = shopdata6.groupby(['id'])['transaction_99'].transform('cumsum')
结果看起来还不错,但这是正确的吗?
答案 0 :(得分:0)
您的代码应简化:
s = (shopdata6['dept']==99).astype(int)
shopdata6['transaction_99'] = s.groupby(shopdata6['id']).cumsum()
print (shopdata6)
id dept date purchase purchase_count_dept99(desired) transaction_99
0 id1 199 date1 $10 0 0
1 id1 99 date1 $10 1 1
2 id1 100 date1 $50 1 1
3 id1 99 date2 $30 2 2
4 id2 100 date1 $10 0 0
5 id2 99 date1 $10 1 1
6 id3 99 date3 $10 1 1
答案 1 :(得分:0)
如果我正确理解您的问题,则需要.cumcount()
df["transaction_99"] = df[df["dept"] == 99].groupby("id").cumcount()
要使计数从1开始,只需添加即可。
df["transaction_99"] = df["transaction_99"] + 1
答案 2 :(得分:0)
shopdata6['transaction_99'] = np.where(shopdata6['dept']==99, 1, 0)
shopdata6['transaction_99'] = shopdata6.groupby(['id'])['transaction_99'].transform('cumsum')