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
276 views
in Technique[技术] by (71.8m points)

python - Cumulative product using Numpy or Scipy

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]

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?

question from:https://stackoverflow.com/questions/65907411/multiply-all-the-elements-of-an-array-by-groups-without-using-a-loop-with-python

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

1 Answer

0 votes
by (71.8m points)

You can use numpy.cumprod:

>>> np.cumprod(arr)
array([      1,       2,       6,      24,     120,     720,    5040,
         40320,  362880, 3628800], dtype=int32)

Just in case you don't want to use numpy and you would rather stay in pure python (perhaps because you want pythons unlimited precision integers and don't care too much about speed) you could also use itertools.accumulate:

>>> import itertools
>>> import operator

>>> list(itertools.accumulate(arr, operator.mul))
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

Note: The itertools.accumulate function requires python3.


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

...