简体   繁体   中英

pandas rolling_apply cumprod

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?

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()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM