Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
835 views
in Technique[技术] by (71.8m points)

python - Cumulative or Rolling Product in a Dataframe

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...