gpt4 book ai didi

Python Pandas 获取排除当前行的累积和(cumsum)

转载 作者:太空宇宙 更新时间:2023-11-03 19:52:22 25 4
gpt4 key购买 nike

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

我的代码如下所示。仅使用 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/59756019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com