我正在学习 numpy 包,我找到了这个代码示例:
import numpy as np
a = np.array([[1,2,3], [4,5,6]])
np.add.reduce(a)
我无法理解的是点符号:
np.add.reduce(a)
对比,例如
np.add(a,5)
我明白 add 和 reduce 的作用,但是 add 是什么?什么是减少?
请您参考如下方法:
“减少”是一个笼统的概念,我在 https://docs.python.org/3/library/functools.html#functools.reduce 找到了一个不错的定义。
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.
Numpy 的 ufunc reduce 记录在 https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduce.html
Reduces a’s dimension by one, by applying ufunc along one axis.
因此 np.add.reduce(a)(也称为 np.add.reduce(a, axis=0))将调用 np.在,然后将结果添加到a[0]和a[1]上添加a[2]等,直到它包含所有 len(a) 元素。
结果:array([5, 7, 9])
np.add(x, y) 基本上是 x + y。 np.add.reduce(a, axis=0) 基本上是 np.sum(a, axis=0)。
np.add.reduce(a, axis=1) 添加 a[:, 0] 到 a[:, 1] ,然后将结果添加到 a[:, 2],依此类推。`
结果:array([ 6, 15])
