Python Pandas 获取不包括当前行的累积和(cumsum)

标签 python pandas

我正在尝试获取给定列的累计计数,该列不包括数据框中的当前行。

我的代码如下所示。仅使用 cumsum() 的问题在于它在计数中包含了当前行。

我希望 df['ExAnte Good Year Count'] 在 ExAnte 的基础上计算 cumsum - 即。从计数中排除当前行。

d = {
      'Year':[2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008], 
      'Good Year':[1, 0, 1, 0, 0, 1, 1, 1, 0]
      'Year Type':['X', 'Y', 'Z', 'Z', 'Z', 'X', 'Y', 'Z', 'Z']
    }

df = pd.DataFrame(d, columns=['Year','Good Year'])
df['ExAnte Good Year Count'] = df['Good Year'].cumsum()

更新查询: 我还想计算按年份类型分组的“好年头”的累计值。我试过了……

'df['Good Year'].groupby(['Year Type']).shift().cumsum()'

...但是我收到一条错误消息“KeyError:'Year Type'”

最佳答案

这个怎么样?

df['ExAnte Good Year Count'] = df['Good Year'].shift().cumsum()

结果应该是这样的:

   Year  Good Year  ExAnte Good Year Count
0  2000          1                     NaN
1  2001          0                     1.0
2  2002          1                     1.0
3  2003          0                     2.0
4  2004          0                     2.0
5  2005          1                     2.0
6  2006          1                     3.0
7  2007          1                     4.0
8  2008          0                     5.0

关于Python Pandas 获取不包括当前行的累积和(cumsum),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47723875/

相关文章:

python - 根据不同数据框中的匹配值将摘要列添加到 Pandas 数据框中

python - 没有名为 'openpyxl' 的模块 - Python 3.4 - Ubuntu

python - Python 中的重构(在 Eclipse 中提取新方法)

python - Numpy 无法在内存中存储大于 1GB 的矩阵

python - 将文本文件转换为 Pandas 数据框

python - Numpy 舍入问题

python - 嵌套 for 循环以列出具有不同 "if"条件的理解

python - Docker 组合多个容器

python - 使用自定义大小的间隔和聚合函数连接两个 pandas 数据框

python - DataFrame 按元素除以行总和