简体   繁体   English

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

[英]Python Pandas Get a Cumulative Sum (cumsum) which excludes the current row

I am trying to get a cumulative count of a given column that excludes the current row in the dataframe.我正在尝试获取排除数据框中当前行的给定列的累积计数。

My code is shown below.我的代码如下所示。 The problem with using cumsum() only is that it includes the current row in the count.仅使用 cumsum() 的问题在于它包括计数中的当前行。

I want df['ExAnte Good Year Count'] to calculate cumsum on an ExAnte basis - ie.我希望 df['ExAnte Good Year Count'] 以 ExAnte 为基础计算 cumsum - 即。 excluding the current row from the count.从计数中排除当前行。

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()

UPDATED QUERY: I would also like to count the cumsum of 'Good Years', grouped by Year Type.更新的查询:我还想计算按年份类型分组的“好年”的总和。 I have tried...我努力了...

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

...but I get an error which says 'KeyError:'Year Type' ...但我收到一个错误,上面写着'KeyError:'Year Type'

what about this one?这个呢?

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

The result should be the following:结果应如下所示:

   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
df['Yourcol']=df.groupby('Year Type',sort=False)['Good Year'].apply(lambda x : x.shift().cumsum())
df
Out[283]: 
   Good Year  Year Year Type  Yourcol
0          1  2000         X      NaN
1          0  2001         Y      NaN
2          1  2002         Z      NaN
3          0  2003         Z      1.0
4          0  2004         Z      1.0
5          1  2005         X      1.0
6          1  2006         Y      0.0
7          1  2007         Z      1.0
8          0  2008         Z      2.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM