How to compute cumulative sum of previous N rows in pandas?

后端 未结 3 926
青春惊慌失措
青春惊慌失措 2020-12-09 09:16

I am working with pandas, but I don\'t have so much experience. I have the following DataFrame:

          A
0       NaN
1      0.00
2      0.00
3      3.33
4         


        
相关标签:
3条回答
  • 2020-12-09 09:50

    you might have to do it the hard way

    B = []
    i =0
    m_lim = 11
    while i<len(A):
        if i<m_lim:
          B.append(sum(A[0:i]))
        if i>=m_lim and i < len(A) -m_lim:
            B.append(sum(A[i-m_lim:i]))
        if i>= len(A) -m_lim:
          B.append(sum(A[i:]))
        i=i+1
    df['B'] = B
    
    0 讨论(0)
  • 2020-12-09 09:53

    Check the pandas.Series.expanding. The series.expanding(min_periods=2).sum()

    will do the job for you. And don't forget to set 0-th element, since it is NaN. I mean,

    accumulation = series.expanding(min_periods=2).sum()
    accumulation[0] = series[0] # or as you like
    
    0 讨论(0)
  • 2020-12-09 10:04

    Call rolling with min_periods=1 and window=11 and sum:

    In [142]:
    df['A'].rolling(min_periods=1, window=11).sum()
    
    Out[142]:
    0       NaN
    1      0.00
    2      0.00
    3      3.33
    4     13.54
    5     20.21
    6     27.21
    7     35.48
    8     41.55
    9     43.72
    10    47.10
    11    49.58
    12    51.66
    13    58.61
    14    55.28
    15    46.82
    16    46.81
    17    49.50
    18    47.96
    19    48.09
    20    48.93
    21    45.87
    22    43.91
    Name: A, dtype: float64
    
    0 讨论(0)
提交回复
热议问题