数据框中的累积或滚动产品 [英] Cumulative or Rolling Product in a Dataframe
问题描述
我有一个带有一列的数据框,我只是想添加另一列,该列采用原始列的滚动乘积.我已经搜索了一段时间,但这似乎是一种基本功能-不确定是否丢失了某些内容.想要将B列作为输出.
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'] =数据['A'].rolling(window = 1).product()
data['B'] = data['A'].rolling(window=1).product()
我从较早时发现了这篇文章,但似乎使用的是rolling_apply,它不再活动了?:
I found this post from earlier but it seems to be using rolling_apply which is no longer active?:
如何在Pandas DataFrame上计算滚动累积产品 a>
我曾尝试在此处使用类似的解决方案,但似乎无法正常工作.
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())
输出:
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
推荐答案
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
这篇关于数据框中的累积或滚动产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!