Pandas- Cumilative Sum Of Previous Row Values
Here is sample dataset: id a 0 5 1 1 5 0 2 5 4 3 5 6 4 5 2 5 5 3 6 9 0 7 9 1 8 9 6 9 9 2 10 9 4 From the dataset, I want to generat
Solution 1:
You can define a functiona like the below:
def cumsum_last3(DF):
nrow=DF.shape[0]
DF["sum"]=0
DF["sum"].iloc[0]=DF["a"].iloc[0]
DF["sum"].iloc[1]=DF["a"].iloc[0]+DF["a"].iloc[1]
for a in range(nrow-2):
cums=np.sum(DF["a"].iloc[a:a+3])
DF["sum"].iloc[a+2]=cums
return DF
DF_cums=cumsum_last3(DF)
DF_cums
Post a Comment for "Pandas- Cumilative Sum Of Previous Row Values"