rafvasq
rafvasq

Reputation: 1510

Given a set indexes, aggregate between each index in dataframe

Given an array of indexes,

array([0, 12, 42, 50, 64, 67, 85, 90, 100]

Is there a way to get a sum of values from a dataframe df specifically between these indexes without looping over df.iloc[i:i+1].sum()?

Upvotes: 0

Views: 79

Answers (1)

Scott Boston
Scott Boston

Reputation: 153470

IIUC, you can use this method:

df = pd.DataFrame(np.arange(0,100))
a = np.array([0, 12, 42, 50, 64, 67, 85, 90, 100])

df.groupby(pd.cut(df.index, a)).sum()

Output:

              0
(0, 12]      78
(12, 42]    825
(42, 50]    372
(50, 64]    805
(64, 67]    198
(67, 85]   1377
(85, 90]    440
(90, 100]   855

Upvotes: 3

Related Questions