Python将获取不包括当前行的累积和(cumsum)
我试图获取给定列的累积计数,该列不包括数据帧中的当前行 我的代码如下所示。仅使用cumsum()的问题在于它在计数中包含当前行 我希望df['ExAnte Good Year Count']在ExAnte基础上计算cumsum,即从计数中排除当前行Python将获取不包括当前行的累积和(cumsum),python,pandas,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]
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
嘿,谢谢。如果我还想添加另一列(例如,年份类型),并应用累积和函数,以便按年份类型获得“好年份”的累积计数,该怎么办。。。?我据此编辑了上述代码。感谢您的反馈。请参阅更新的查询(如上)
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