numpy.prod(a, axis=None, dtype=None, out=None, keepdims=, initial=, where=)
Return the product of array elements over a given axis.
a [array_like]
Input data.
axis [None or int or tuple of ints, optional]
Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.
dtype [dtype, optional]
The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.
out [ndarray, optional]
Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.
keepdims [bool, optional]
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the prod method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
initial [scalar, optional]
The starting value for this product. See reduce for details.
where [array_like of bool, optional]
Elements to include in the product. See reduce for details.
若指定了axis
,把数组a
沿着维度axis
进行切片,并把切片后得到的一系列数组每个对应位置的元素相乘(element-wise product),如果axis
未指定,则对数组进行扁平化后计算所有元素的乘积.
示例1. 把向量或矩阵中所有元素相乘
import numpy as np
mat= np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
print(np.prod(mat))
结果:
216
示例2. 指定 axis,实现某一维度的元素相乘
例如对于二维数组,指定axis=0,则按照行进行切片,然后对应位置相乘(element-wise product),得到的是每一列元素相乘的乘积。
相当于np.multiply.reduce(mat,axis=0)
import numpy as np
mat= np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
print(np.prod(mat,axis=0))
print(np.multiply.reduce(mat,axis=0))
结果:
[ 1 8 27]
[ 1 8 27]
示例3. 指定where,实现只对某些index的元素进行相乘
如果要计算 [1,2,3,4,5,6] 中index为 [0,2,4] 三个元素的乘积
np.prod([1., np.nan, 3.], where=[True, False, True])
结果
3.0