thetinywindow
thetinywindow

Reputation: 71

Cumulative Sum DataFrame (.groupby())

I am trying to get the cumulative sum of 'counter' over the years. Basically, adding the sums for each individual year while maintaining the multi index structure. Help is highly appreciated! :)

df = pd.DataFrame(df_raw[['counter']])
df['listings_per_zip'] = df.groupby(level=[0,1]).sum()
df = df.mean(level=[0,1])

Curren Input (df_raw)

Current Output (df)

(Example) Expected output: Sum for ZIP over the years. For instance, 2018 'listings_per_zip' should be the sum of 2008+2009+...+2017

Upvotes: 0

Views: 74

Answers (1)

thetinywindow
thetinywindow

Reputation: 71

Issue is resolved by the following code:

df['listings_per_zip'] = df.groupby(level=[0,1]).sum().groupby(level=[1]).cumsum()

Upvotes: 1

Related Questions