所发生的一切就是,numpy是第一个(0)轴和唯一一个轴的总和。请考虑以下几点:In [2]: a = np.array([1, 2, 3])
In [3]: a.shape
Out[3]: (3,)
In [4]: len(a.shape) # number of dimensions
Out[4]: 1
In [5]: a1 = a.reshape(3,1)
In [6]: a2 = a.reshape(1,3)
In [7]: a1
Out[7]:
array([[1],
[2],
[3]])
In [8]: a2
Out[8]: array([[1, 2, 3]])
In [9]: a1.sum(axis=1)
Out[9]: array([1, 2, 3])
In [10]: a1.sum(axis=0)
Out[10]: array([6])
In [11]: a2.sum(axis=1)
Out[11]: array([6])
In [12]: a2.sum(axis=0)
Out[12]: array([1, 2, 3])
所以,更明确地说:In [15]: a1.shape
Out[15]: (3, 1)
a1是二维的,“长”轴是第一个。In [16]: a1[:,0] # give me everything in the first axis, and the first part of the second
Out[16]: array([1, 2, 3])
现在,沿着第一个轴求和:In [17]: a1.sum(axis=0)
Out[17]: array([6])
现在,考虑一个不那么简单的二维情况:In [20]: b = np.array([[1,2,3],[4,5,6]])
In [21]: b
Out[21]:
array([[1, 2, 3],
[4, 5, 6]])
In [22]: b.shape
Out[22]: (2, 3)
第一个轴是“行”。沿行求和:In [23]: b.sum(axis=0)
Out[23]: array([5, 7, 9])
第二个轴是“列”。沿列求和:In [24]: b.sum(axis=1)
Out[24]: array([ 6, 15])