我正在尝试获取给定列的累计计数,该列不包括数据框中的当前行。
我的代码如下所示。仅使用 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/