I was expecting the shape to be (1,3) when I sum along axis=0 i.e. rows. But the shape remains same in both cases. Why is that?
>>> arr = np.arange(9).reshape(3,3) >>> arr array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> arr.sum(1) array([ 3, 12, 21]) >>> arr.sum(1).shape (3,) >>> arr.sum(0) array([ 9, 12, 15]) >>> arr.sum(0).shape (3,)Answer1:
An array with the same shape as
a, with the <strong>specified axis removed</strong>.
With one axis removed in both cases, you are left with a singleton tuple.
<em>2 axes - 1 specified axis = 1 axis</em>
True in both gives different shapes, retaining all the axes in the original array with a corresponding change of length along the specified axis:
>>> arr.sum(axis=0, keepdims=True) array([[ 9, 12, 15]]) >>> arr.sum(axis=1, keepdims=True) array([[ 3], , ])Answer2:
Because summing along the axis of a ND array yields a (N-1)D array. This makes sense if you consider that
np.sum([1,2,3]) == 6 # a 0D 'array'
If you want to turn your
arr.sum(1) into a
(1, 3) or
(3, 1) 2D array, then use
s = arr.sum(0)[np.newaxis, :] # (1, 3)
s = arr.sum(1)[:, np.newaxis] # (3, 1)Answer3:
According to <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.sum.html" rel="nofollow">the documentation</a> this is what you'll get:<blockquote>
sum_along_axis : ndarray
An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.</blockquote>
The shape of
arr is indeed
(3,3) and is two-dimensional. If you remove one axis you'll be left with a shape of
(3,) - which is one-dimensional.
An array with shape
(1,3) still has two axes.
numpy.arrays have a logic which is not the same than Matlab or even mathematics. From <a href="https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html" rel="nofollow">here</a> :
Handling of vectors (one-dimensional arrays) For array, the vector shapes 1xN, Nx1, and N are all different things. Operations like A[:,1] return a one-dimensional array of shape N, not a two-dimensional array of shape Nx1. Transpose on a one-dimensional array does nothing.</blockquote>
Numpy story began not with linear algebra, so a one dimension object is always <em>horizontal</em>, cannot be transposed, an so on. It is confusing first time with a different background, but with a lot advantages in other fields. in numpy 2-dim arrays are lines (dim0) of columns(dim1), like for matrix, but selecting a line or a column return always ... a line !
As an example :
In : m=np.arange(6).reshape(3,2) In : m Out: array([[0, 1], [2, 3], [4, 5]]) In : m[0,:] Out: array([0, 1]) In : m[:,0] Out: array([0, 2, 4])
This convention accepted, nothing is very difficult.