0

Hi I have a dataframe with a column and i'd simply like to add another column that takes the rolling product of the original column. I've been googling around for a while but this seems like such a basic functionality - not sure if I'm missing something. Id to like to get Column B as an output.

A   B
1   1
2   2
3   6
4   24
5   120
6   720
7   5040

Im essentially looking for something like this if it existed:

data['B'] = data['A'].rolling(window=1).product()

I found this post from earlier but it seems to be using rolling_apply which is no longer active?:

How to calculate rolling cumulative product on Pandas DataFrame

i've tried using a similar solution here like this but it doesn't seem to be working.

dftest= pd.DataFrame([1,2,3,4,5,6,7],columns=['A'])
dftest['cum']=dftest['A'].rolling(1).apply(lambda x:x.prod())

Output:

   A  cumprod
0  1  1.0
1  2  2.0
2  3  3.0
3  4  4.0
4  5  5.0
5  6  6.0
6  7  7.0
novawaly
  • 1,051
  • 3
  • 12
  • 27
  • Ive serached through the previous posts. The only thing I could find that worked was asked 5 years ago and used rolling_apply which no longer seems to be an option – novawaly Jul 20 '18 at 18:11
  • 1
    You say "rolling product", but that looks a lot more like an expanding product to me. A rolling product with a window of 1 would just be the series itself, no? – DSM Jul 20 '18 at 18:12
  • The answer from the dupe hasn't been in pandas for a while, and while this may still be a dupe, there has to be a better target – user3483203 Jul 20 '18 at 18:13
  • @DSM you are actually right - i need an expanding product. – novawaly Jul 20 '18 at 18:22

1 Answers1

3

Seems like you want cumprod

df = pd.DataFrame({'v':[1,2,3,4,5,6]})
df['prod'] = df.v.cumprod()

    v   prod
0   1   1
1   2   2
2   3   6
3   4   24
4   5   120
5   6   720

May also do

df.v.expanding().agg(lambda a:a.prod())

0      1.0
1      2.0
2      6.0
3     24.0
4    120.0
5    720.0
rafaelc
  • 57,686
  • 15
  • 58
  • 82