prod()
函数沿着指定的轴或跨所有轴计算数组元素的乘积。
示例
import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
# use prod() to calculate product of array1 elements
result = np.prod(array1)
print(result)
# Output : 15
prod() 语法
prod()
的语法是:
numpy.prod(array, axis = None, dtype = None, out = None, keepdims = <no value>)
prod() 参数
prod()
函数接受以下参数:
array
- 输入数组axis
(可选) - 计算乘积的轴dtype
(可选) - 返回输出的数据类型out
(可选) - 用于存储结果的输出数组keepdims
(可选) - 是否保留输入数组的维度 (bool
)
prod() 返回值
prod()
函数返回数组元素的乘积。
示例 1:二维数组的 prod()
axis
参数定义了如何在二维数组中找到元素的乘积。
- 如果
axis
=None
,则将数组展平,并返回展平数组的乘积。 - 如果
axis
= 0,则按列计算乘积。 - 如果
axis
= 1,则按行计算乘积。
import numpy as np
# create a 2D array
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# calculate the product along different axes
result_none = np.prod(arr, axis=None)
result_cols = np.prod(arr, axis=0)
result_rows = np.prod(arr, axis=1)
print("Product of all elements (axis=None):", result_none)
print("Product along columns (axis=0):", result_cols)
print("Product along rows (axis=1):", result_rows)
输出
Product of all elements (axis=None): 362880 Product along columns (axis=0): [ 28 80 162] Product along rows (axis=1): [ 6 120 504]
示例 2:使用 out 将结果存储在所需位置
import numpy as np
array1 = np.array([[10, 17, 25],
[15, 11, 22],
[11, 19, 20]])
# create an empty array
array2= np.array([0, 0, 0])
# pass the 'out' argument to store the result in array2
np.prod(array1, axis = 0, out = array2)
print(array2)
输出
[ 1650 3553 11000]
在此,在指定 out=array2
后,array1 沿 axis=0
的乘积结果被存储在 array2 数组中。
示例 3:带 keepdims 的 prod()
当 keepdims = True
时,结果数组的维度与输入数组的维度匹配。
import numpy as np
array1 = np.array([[10, 17, 25],
[15, 11, 22]])
print('Dimensions of original array: ', array1.ndim)
result = np.prod(array1, axis = 1)
print('\n Without keepdims: \n', result)
print('Dimensions of array: ', result.ndim)
# set keepdims to True to retain the dimension of the input array
result = np.prod(array1, axis = 1, keepdims = True)
print('\n With keepdims: \n', result)
print('Dimensions of array: ', result.ndim)
输出
Dimensions of original array: 2 Without keepdims: [4250 3630] Dimensions of array: 1 With keepdims: [[4250] [3630]] Dimensions of array: 2
如果不使用 keepdims
,结果只是一个包含索引的一维数组。
使用 keepdims
时,结果数组具有与输入数组相同的维度数。