Why does the shape remains same when I sum a square numpy array along either directions?


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,)


numpy.sum returns:


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>

However, passing keepdims as 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], [12], [21]])


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)


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:



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.


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.


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 [1]: m=np.arange(6).reshape(3,2) In [2]: m Out[2]: array([[0, 1], [2, 3], [4, 5]]) In [3]: m[0,:] Out[3]: array([0, 1]) In [4]: m[:,0] Out[4]: array([0, 2, 4])

This convention accepted, nothing is very difficult.


  • numpy array directional mean without dimension reduction
  • Excel VBA changing color for CommandButton
  • Plotly error: Invalid 'figure_or_data' argument
  • R, export a file to keynote
  • Delete pictures in PowerPoint using VBA macro
  • Should overloaded methods with value types be consolidated into a generic method?
  • UIScrollView ContentSize.height is 0.0000 by default?
  • MySQL Views: Referencing one calculated field (by name) in another calculated field
  • How to debug a Pivot Chart Macro?
  • How to draw rectangles and assign macros to them from VBA?
  • Keeping rows with at defined numbers of NAs in a dataframe [duplicate]
  • Data.table: Add rows for missing combinations of 2 factors without losing associated descriptive fac
  • Plotly python how to draw unbounded lines and spans?
  • Objective C difference between self.variable and variable assignments
  • TextDecorations not being applied to TextBlock during a TreeViewItem Style Trigger
  • Application.AddMessageFilter - how to read exactly what keys were pushed?
  • Bundler using old version
  • Using VBA to select a dynamic range of cells and create a chart
  • How to calculate total across columns but one?
  • Why do GeoJSON features appear like a negative photo of the features themselves?
  • Change device language on Android 6.0 (Android M)
  • Invert string in Rust
  • How to use function wrapper in mustache.php?
  • Who propagate bugfixes across branches (corporate development)?
  • xcode don't localize specific strings
  • Zoom in and out of jPanel
  • ilmerge with a PFX file
  • Statically linking a C++ library to a C# process using CLI or any other way
  • Calling of Constructors in a Java
  • Traverse Array and Display in markup
  • Transpose CSV data with awk (pivot transformation)
  • retrieve vertices with no linked edge in arangodb
  • Why can't I rebase on to an ancestor of source changesets if on a different branch?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Change div Background jquery
  • apache spark aggregate function using min value
  • python draw pie shapes with colour filled
  • Running Map reduces the dimensions of the matrices
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?