Given a DataFrame with an ID column and corresponding values column, how can I aggregate (let's say sum) the values within blocks of repeating IDs?
Example DF:
import numpy as np
import pandas as pd
df = pd.DataFrame(
{'id': ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'a', 'a', 'b', 'a', 'b', 'b', 'b'],
'v': np.ones(15)}
)
Note that there's only two unique IDs, so a simple groupby('id') won't work. Also, the IDs don't alternate/repeat in a regular manner. What I came up with was to recreate the index, to represent the blocks of changed IDs:
# where id changes:
m = [True] + list(df['id'].values[:-1] != df['id'].values[1:])
# generate a new index from m:
idx, i = [], -1
for b in m:
if b:
i += 1
idx.append(i)
# set as index:
df = df.set_index(np.array(idx))
# now I can use groupby:
df.groupby(df.index)['v'].sum()
# 0 5.0
# 1 3.0
# 2 2.0
# 3 1.0
# 4 1.0
# 5 3.0
This re-creation of the index feels sort-of not how you'd do this in pandas. What did I miss? Is there a better way to do this?