【问题标题】:Weighted cumulative sum python加权累积和python
【发布时间】:2018-01-04 13:36:19
【问题描述】:

我在查找类似于累积总和的函数时遇到问题,只是我希望它加权。因此,使用外部 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 numpy


【解决方案1】:

注意:我使用的是Python 3.6.0

您可以尝试使用itertoolshttps://docs.python.org/3/library/itertools.html

itertools.accumulate 函数被证明可能比 np.cumsum 更快:https://stackoverflow.com/a/39534850/7175945

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,我认为这应该是你正在寻找的,否则你已经写的也是一个可行的选择。

【讨论】:

    猜你喜欢
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    相关资源
    最近更新 更多