【问题标题】:Pandas cumulative sum of all previous dates by group [duplicate]Pandas 按组划分的所有先前日期的累积总和[重复]
【发布时间】:2019-09-27 06:13:23
【问题描述】:

我有一个这样的 Pandas 数据框:

df = pd.DataFrame({
    'Date': ['2018-04-01', '2018-05-01', '2018-06-01', '2018-07-01', '2018-08-01'],
    'Product': ['a', 'a', 'a', 'b', 'b'],
    'Volumes': [10,30,40,50,60]})

Date       Product   Volumes
2018-04-01  a        10
2018-05-01  a        30
2018-06-01  a        40
2018-07-01  b        50
2018-08-01  b        60

我想创建一个列,该列仅对同一产品的所有前几个月的所有交易量求和。

期望的输出是:


df = pd.DataFrame({
    'Date': ['2018-04-01', '2018-05-01', '2018-06-01', '2018-07-01', '2018-08-01'],
    'Product': ['a', 'a', 'a', 'b', 'b'],
    'Volumes': [10,30,40,50,60],
    'Result': [10,40,80,50,110] })


Date        Product   Volumes   Result
2018-04-01   a         10       10
2018-05-01   a         30       40
2018-06-01   a         40       80
2018-07-01   b         50       50
2018-08-01   b         60       110

有人对如何做到这一点有任何建议吗?

谢谢!

【问题讨论】:

  • 使用df['Result'] = df.groupby('Product')['Volumes'].cumsum()
  • 检查this

标签: python pandas


【解决方案1】:

用途:

df['Result']=df.groupby('Product')['Volumes'].cumsum()

         Date Product  Volumes  Result
0  2018-04-01       a       10      10
1  2018-05-01       a       30      40
2  2018-06-01       a       40      80
3  2018-07-01       b       50      50
4  2018-08-01       b       60     110

【讨论】:

    猜你喜欢
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 2018-05-30
    • 2020-09-13
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    相关资源
    最近更新 更多