2

I am trying to get a rolling cumulative product to a series in pandas. My input series is:

   s
0  1
1  2
2  3
3  4
4  5
5  6

I would like to get a resulting series that gives me the cumulative product of the previous 'n' values. So if 'n' were 3, I would like to get:

   s
0  n/a
1  n/a
2  6
3  24
4  60
5  120

The code I have come up with uses rolling_apply and a lambda function and produces a TypeError:

import pandas as pnd
df = pnd.DataFrame()
df['s'] = [1,2,3,4]
print (df)
print (pnd.rolling_apply(df.s,2,lambda x : x.cumprod()))

TypeError: only length-1 arrays can be converted to Python scalars

Does anyone know how to do this?

feetwet
  • 3,248
  • 7
  • 46
  • 84
nitin
  • 7,234
  • 11
  • 39
  • 53

1 Answers1

3

Thanks to user2357112. This is the code that I came up that works...

import pandas as pnd
df = pnd.DataFrame()
df['s'] = [1,2,3,4, 5, 6]
print (df)
print (pnd.rolling_apply(df.s,3,lambda x : x.prod()))
nitin
  • 7,234
  • 11
  • 39
  • 53