python中几天的累计总和

时间:2019-02-27 10:31:20

标签: python pandas pandas-groupby

我有以下数据框:

        date      money
0     2018-01-01     20
1     2018-01-05     30
2     2018-02-15     7
3     2019-03-17     150
4     2018-01-05     15
...
2530  2019-03-17     350

我需要:

[(2018-01-01,20),(2018-01-05,65),(2018-02-15,72),...,(2019-03-17,572)]

因此,我需要整天累积金额: 到目前为止,我已经尝试了很多事情,而最接近的Ithink是:

graph_df.date = pd.to_datetime(graph_df.date)
temporary = graph_df.groupby('date').money.sum()
temporary = temporary.groupby(temporary.index.to_period('date')).cumsum().reset_index()

但这给了我ValueError:无效的频率:日期

有人可以帮忙吗?

谢谢

3 个答案:

答案 0 :(得分:2)

我认为您不需要第二组。您可以简单地在列中添加累计金额。

这对我有用:

import pandas as pd
df = pd.DataFrame({'date': ['01-01-2019','04-06-2019', '07-06-2019'], 'money': [12,15,19]})
df['date'] = pd.to_datetime(df['date']) # this is not strictly needed

tmp = df.groupby('date')['money'].sum().reset_index()
tmp['money_sum'] = tmp['money'].cumsum()

不需要将日期列转换为实际日期。

答案 1 :(得分:1)

list(map(tuple, df.groupby('date', as_index=False)['money'].sum().values))

修改

df = pd.DataFrame({'date': ['2018-01-01', '2018-01-05', '2018-02-15', '2019-03-17', '2018-01-05'],
                   'money': [20, 30, 7, 150, 15]})

#df['date'] = pd.to_datetime(df['date'])
#df = df.sort_values(by='date')

temporary = df.groupby('date', as_index=False)['money'].sum()
temporary['money_cum'] = temporary['money'].cumsum()

结果:

>>> list(map(tuple, temporary[['date', 'money_cum']].values))
[('2018-01-01', 20),
 ('2018-01-05', 65),
 ('2018-02-15', 72),
 ('2019-03-17', 222)]

答案 2 :(得分:0)

您可以尝试使用df.groupby('date').sum()

示例数据框:

df
         date  money
0  01/01/2018     20
1  05/01/2018     30
2  15/02/2018      7
3  17/03/2019    150
4  05/01/2018     15
5  17/03/2019    550
6  15/02/2018     13



df['cumsum'] = df.money.cumsum()
list(zip(df.groupby('date').tail(1)['date'], df.groupby('date').tail(1)['cumsum']))

[('01/01/2018', 20),
 ('05/01/2018', 222),
 ('17/03/2019', 772),
 ('15/02/2018', 785)]