Tobitor
Tobitor

Reputation: 1508

How to get a new column with sum of even/odd/kth rows?

I have this pandas series:

ts = pd.Series([1, 2, 3, 4, 5, 6, 7, 8])

What I would like to get is a dataframe which contains another column with the sum of rows 0, 2, 4, 6 and for 1, 3, 5 and 7 (that means, one row is left out when creating the sum).

In this case, this means a new dataframe should look like this one:

index ts sum
0 1 16
1 2 20
2 3 16
3 4 20
4 5 16
5 6 20
6 7 16
7 8 20

How could I do this?

Upvotes: 3

Views: 132

Answers (1)

jezrael
jezrael

Reputation: 863156

Use modulo by k for each kth rows:

k = 2
df = ts.to_frame('ts')
df['sum'] = df.groupby(ts.index % k).transform('sum')
#if not default RangeIndex
#df['sum'] = df.groupby(np.arange(len(ts)) % k).transform('sum')
print (df)
   ts  sum
0   1   16
1   2   20
2   3   16
3   4   20
4   5   16
5   6   20
6   7   16
7   8   20

Upvotes: 4

Related Questions