Python cumsum of rows up until n-1

huangapple go评论73阅读模式
英文:

Python cumsum of rows up until n-1

问题

我正在尝试获取数据框中一列的累积总和,但不包括我们感兴趣的行。数据框按年份拆分。

我已经能够在Excel中完成此操作,下面是我想要实现的效果。

Python cumsum of rows up until n-1

我已经接近实现了,使用以下代码:

df1['CumSum'] = df1.groupby('Year')['Value'].cumsum()

但这会返回下面的结果:

Python cumsum of rows up until n-1

英文:

I am trying to get a cumulative sum of a column in a dataframe for all rows except the row we are interested in. The dataframe is split by year.

I have been able to do this in excel and the below is what I am trying to achieve.

Python cumsum of rows up until n-1

I am close by using

df1['CumSum'] = df1.groupby('Year')['Value'].cumsum()

but this will return

Python cumsum of rows up until n-1

答案1

得分: 0

你可以在组上使用 shift 来将结果向前移动一个位置:

df["CumSum"] = df.groupby("Year", group_keys=False)["Value"].apply(lambda x: x.cumsum().shift(1))
英文:

You can use a shift on the groups to shift the result by one:


df["CumSum"] = df.groupby("Year", group_keys=False)["Value"].apply(lambda x: x.cumsum().shift(1))

huangapple
  • 本文由 发表于 2023年2月23日 23:07:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定