Python中的 numpy.cumprod()
当我们想要计算数组元素在给定轴上的累积乘积时,使用numpy.cumprod()
函数。
Syntax : numpy.cumprod(arr, axis=None, dtype=None, out=None)
Parameters :
arr : [array_like] Array containing numbers whose cumulative product is desired. If arr is not an array, a conversion is attempted.
axis : Axis along which the cumulative product is computed. The default is to compute the product of the flattened array.
dtype : Type of the returned array, as well as of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of arr, unless arr has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead.
out : [ndarray, optional] A location into which the result is stored.
-> If provided, it must have a shape that the inputs broadcast to.
-> If not provided or None, a freshly-allocated array is returned.
Return : A new array holding the result is returned unless out is specified, in which case it is returned.
代码#1:工作
# Python program explaining
# numpy.cumprod() function
import numpy as geek
in_num = 10
print ("Input number : ", in_num)
out_prod = geek.cumprod(in_num)
print ("cumulative product of input number : ", out_prod)
输出 :
Input number : 10
cumulative product of input number : [10]
代码#2:
# Python program explaining
# numpy.cumprod() function
import numpy as geek
in_arr = geek.array([[2, 4, 6], [1, 3, 5]])
print ("Input array : ", in_arr)
out_prod = geek.cumprod(in_arr)
print ("cumulative product of array elements: ", out_prod)
输出 :
Input array : [[2 4 6]
[1 3 5]]
cumulative product of array elements: [ 2 8 48 48 144 720]
代码#3:
# Python program explaining
# numpy.cumprod() function
import numpy as geek
in_arr = geek.array([[2, 4, 6], [1, 3, 5]])
print ("Input array : ", in_arr)
out_prod = geek.cumprod(in_arr, axis = 1)
print ("cumulative product of array elements taking axis 1: ", out_prod)
输出 :
Input array : [[2 4 6]
[1 3 5]]
cumulative product of array elements taking axis 1: [[ 2 8 48]
[ 1 3 15]]