PythonPandas得到一个累计和(cumsum),不包括curren

2024-04-24 19:37:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图获得一个给定列的累计计数,该列不包括数据帧中的当前行。在

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

我想要df['ExAnte Good Year Count']在ExAnte的基础上计算累计累计数,即从计数中排除当前行。在

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

更新的查询: 我还想计算“好年份”的累计数,按年份类型分组。我试过。。。在

^{pr2}$

…但是我得到一个错误,上面写着'keyrerror:'Year Type'


Tags: 数据代码dataframedftypecountyear基础
2条回答
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

这个怎么样?在

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

结果如下:

^{pr2}$

相关问题 更多 >