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

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


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       NaN1      0.002      0.003      3.334     13.545     20.216     27.217     35.488     41.559     43.7210    47.1011    49.5812    51.6613    58.6114    55.2815    46.8216    46.8117    49.5018    47.9619    48.0920    48.9321    45.8722    43.91Name: A, dtype: float64


you might have to do it the hard way

B = []i =0m_lim = 11while 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+1df['B'] = B


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