【问题标题】:cumulative sum and adding rows where instance does not exist累积总和并添加实例不存在的行
【发布时间】:2019-08-05 13:01:43
【问题描述】:

我正在创建一个具有累积总和的非数据透视表。

数据如下:

Year     Period     Amount    
2011        1         10    
2011        2         15    
2011        3         8   
2012        1         20    
2012        3         10    
2012        4         5   

我要加一个累计和:

Year     Period     Cumulative Amount   
2011        1         10    
2011        2         25  
2011        3         33   
2012        1         20   
2012        3         30   
2012        4         35   

我为这个累积总和编写了代码,但我的问题是,在 2012 年第 2 期的实例中,这些没有记录,因此不会出现。

在没有记录且数量 = 0 的情况下添加行的最简单方法是什么?

对于 2011 年,需要有 2019 - 2011 + 1 = 9 个时期
2012 年需要有 2019 - 2012 + 1 = 8 个时期
… 等等。

为了获得累积总和,我做了以下操作:

py_data = df['Amount'].groupby([df['Year'], df['Period']).sum().reset_index()

py_data['cumsum'] = py_data["'Amount'"].groupby([py_data['Period']]).cumsum()

【问题讨论】:

  • 您需要添加缺失的行吗?但输出不是2012 2 0。还是只有 cumsum ?

标签: python python-3.x pandas dataframe jupyter-notebook


【解决方案1】:

做:

df['Cumulative_Amount'] = df.groupby('Year')['Amount'].cumsum()

输出:

   Year  Amount  Period  Cumulative_Amount
0  2011      10       1                 10
1  2011      15       2                 25
2  2011       8       3                 33
3  2012      20       1                 20
4  2012      10       3                 30
5  2012       5       4                 35

【讨论】:

  • 您仍然缺少 2012 年的期间 2。我希望出现一个新行,其中包含 2012 年和第 2 期金额。
猜你喜欢
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 2018-05-13
  • 1970-01-01
  • 2017-09-16
相关资源
最近更新 更多