繁体   English   中英

加权累计和python

[英]Weighted cumulative sum python

我在查找类似于累积总和的函数时遇到问题,只是我希望对它加权。 因此,使用外部for循环看起来像这样:

discount_rate = 0.95 
rewards = [0, 0, 10] # want to translate to: [9, 9.5, 10] (approximation)

reversed_rewards = [10, 0, 0]
new_rewards = [0] * len( rewards)

previus = 0
for index in range( len( rewards)):
     new_rewards[ index] = reversed_rewards[ index] + previus * discount_rate
     previus = new_rewards[ index]

print( list( reversed( new_rewards)))

但是,如果您有较大的奖励阵列,则这是一种慢速版本。 是否有任何现有功能可以更快地做到这一点?

注意:我正在使用Python 3.6.0

您可以尝试使用itertoolshttps : itertools

结果表明itertools.accumulate函数可能比np.cumsum更快: https : np.cumsum

from itertools import accumulate

def weighted():
    discount_rate = 0.95 #your discount rate
    rewards = [0, 0, 10] # want to translate to: [9, 9.5, 10](approximation)
    reversed_rewards = rewards[::-1] #list reversal
    acc = list(accumulate(reversed_rewards, lambda x,y: x*discount_rate + y))
    return acc[::-1] 

print(weighted())

我认为如果您真的不想使用numpy ,那么这应该是您正在寻找的东西,否则您已经编写的内容也是可行的选择。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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