所以我在使用熊猫查找累计金额时遇到一些问题。
我有一个这样的数据框:
df = pd.DataFrame({
'Date': ['2018-04-01', '2018-04-01', '2018-04-01', '2018-05-01', '2018-05-01','2018-05-01','2018-04-01','2018-05-01'],
'Category': ['AA', 'AA', 'AA', 'AA', 'AA','AA','AA','AA'],
'Product': ['a', 'a', 'a', 'a', 'a','a','x','x'],
'Volumes': [10,30,40,50,60,10,1,2]})
Date Category Product Volumes
2018-04-01 AA a 10
2018-04-01 AA a 30
2018-04-01 AA a 40
2018-05-01 AA a 50
2018-05-01 AA a 60
2018-05-01 AA a 10
2018-04-01 AA x 1
2018-05-01 AA x 2
也就是说,某些产品在同一日期重复,而某些产品是唯一的。
我想通过这种方式找到累计金额:
df = pd.DataFrame({
'Date': ['2018-04-01', '2018-04-01', '2018-04-01', '2018-05-01', '2018-05-01','2018-05-01','2018-04-01','2018-05-01'],
'Category': ['AA', 'AA', 'AA', 'AA', 'AA','AA','AA','AA'],
'Product': ['a', 'a', 'a', 'a', 'a','a','x','x'],
'Volumes': [80,80,80,190,190,190,1,3]})
Date Category Product Volumes
2018-04-01 AA a 80
2018-04-01 AA a 80
2018-04-01 AA a 80
2018-05-01 AA a 200
2018-05-01 AA a 200
2018-05-01 AA a 200
2018-04-01 AA x 1
2018-05-01 AA x 3
其中80是4月份的总量之和,200是4月和5月的总量之和。
我尝试了一个简单的
df.groupby(['Category', 'Product'])['Volumes'].agg(['sum']).reset_index()```
But that doesnt give me the desired output.
Any suggestions?
答案 0 :(得分:3)
更新,在cumsum
之后使用sum
,然后再返回merge
s=df.groupby([df['Date'].dt.month,df['Category'],df['Product']])['Volumes'].sum().reset_index()
s['New']=s.groupby(['Category','Product'])['Volumes'].cumsum()
df=df.assign(Date=df.Date.dt.month,Date1=df.Date).merge(s.drop('Volumes',1),on=['Date','Category','Product'])
df
Out[575]:
Date Category Product Volumes Date1 New
0 4 AA a 10 2018-04-01 80
1 4 AA a 30 2018-04-01 80
2 4 AA a 40 2018-04-01 80
3 5 AA a 50 2018-05-01 200
4 5 AA a 60 2018-05-01 200
5 5 AA a 10 2018-05-01 200
6 4 AA x 1 2018-04-01 1
7 5 AA x 2 2018-05-01 3
答案 1 :(得分:0)
您可以使用两个单独的groupby
呼叫来获得所需的答案:
df['new'] = df.groupby(['Category','Product'])['Volumes'].transform('cumsum')
df['new'] = df.groupby(['Date','Category','Product'])['new'].transform('max')