本文介绍了使用Numpy或Scipy的累积产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个一维numpy数组,希望将其转换为其累积积.天真的实现是这样的:
I have a 1-D numpy array that I wish to convert it to its cumulative product. A naive implementation would be this:
import numpy as np
arr = [1,2,3,4,5,6,7,8,9,10]
c_sum = [np.prod(arr[:i]) for i in range(1, len(arr) + 1)]
# c_sum = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
但是,当 arr
的大小变得很大时,这可能会变慢.我怀疑使用 Numpy
或 Scipy
阵列魔术之一可能会有更有效的方法.有人可以告诉我该怎么做吗?
However this could get slow when the size of arr
gets very large. I suspect that there might be a more efficient way using one of the Numpy
or Scipy
array magics. Can someone show me how to do it?
推荐答案
您可以使用 numpy.cumprod
:
You can use numpy.cumprod
:
>>> np.cumprod(arr)
array([ 1, 2, 6, 24, 120, 720, 5040,
40320, 362880, 3628800], dtype=int32)
以防万一您不想使用numpy并宁愿呆在纯python中(也许是因为您想要python不受限制的精度整数并且不太在乎速度),您也可以使用 itertools.accumulate
:
>>> import itertools
>>> import operator
>>> list(itertools.accumulate(arr, operator.mul))
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
注意: itertools.accumulate
函数需要python3.
Note: The itertools.accumulate
function requires python3.
这篇关于使用Numpy或Scipy的累积产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!