Take the sum of every N rows in a pandas series

前端 未结 1 1505
说谎
说谎 2020-12-06 09:46

Suppose

s = pd.Series(range(50))

0      0
1      1
2      2
3      3
...
48     48
49     49

How can I get the new se

相关标签:
1条回答
  • 2020-12-06 10:19

    GroupBy.sum

    N = 5
    s.groupby(s.index // N).sum()
         
    0     10
    1     35
    2     60
    3     85
    4    110
    5    135
    6    160
    7    185
    8    210
    9    235
    dtype: int64
    

    Chunk the index into groups of 5 and group accordingly.


    numpy.reshape + sum

    If the size is a multiple of N (or 5), you can reshape and add:

    s.values.reshape(-1, N).sum(1)
    # array([ 10,  35,  60,  85, 110, 135, 160, 185, 210, 235])
    

    numpy.add.at

    b = np.zeros(len(s) // N)
    np.add.at(b, s.index // N, s.values)
    b
    # array([ 10.,  35.,  60.,  85., 110., 135., 160., 185., 210., 235.])
    
    0 讨论(0)
提交回复
热议问题