Setup

consider the numpy array a

a = np.arange(30).reshape(2, 3, 5)
print(a)

[[[ 0  1  2  3  4]
  [ 5  6  7  8  9]
  [10 11 12 13 14]]

 [[15 16 17 18 19]
  [20 21 22 23 24]
  [25 26 27 28 29]]]

Where are the dimensions?

The dimensions and positions are highlighted by the following

            p  p  p  p  p
            o  o  o  o  o
            s  s  s  s  s

     dim 2  0  1  2  3  4

            |  |  |  |  |
  dim 0     โ†“  โ†“  โ†“  โ†“  โ†“
  ----> [[[ 0  1  2  3  4]   <---- dim 1, pos 0
  pos 0   [ 5  6  7  8  9]   <---- dim 1, pos 1
          [10 11 12 13 14]]  <---- dim 1, pos 2
  dim 0
  ---->  [[15 16 17 18 19]   <---- dim 1, pos 0
  pos 1   [20 21 22 23 24]   <---- dim 1, pos 1
          [25 26 27 28 29]]] <---- dim 1, pos 2
            โ†‘  โ†‘  โ†‘  โ†‘  โ†‘
            |  |  |  |  |

     dim 2  p  p  p  p  p
            o  o  o  o  o
            s  s  s  s  s

            0  1  2  3  4

Dimension examples:

This becomes more clear with a few examples

a[0, :, :] # dim 0, pos 0

[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]

a[:, 1, :] # dim 1, pos 1

[[ 5  6  7  8  9]
 [20 21 22 23 24]]

a[:, :, 3] # dim 2, pos 3

[[ 3  8 13]
 [18 23 28]]

sum

explanation of sum and axis
a.sum(0) is the sum of all slices along dim 0

a.sum(0)

[[15 17 19 21 23]
 [25 27 29 31 33]
 [35 37 39 41 43]]

same as

a[0, :, :] + \
a[1, :, :]

[[15 17 19 21 23]
 [25 27 29 31 33]
 [35 37 39 41 43]]

a.sum(1) is the sum of all slices along dim 1

a.sum(1)

[[15 18 21 24 27]
 [60 63 66 69 72]]

same as

a[:, 0, :] + \
a[:, 1, :] + \
a[:, 2, :]

[[15 18 21 24 27]
 [60 63 66 69 72]]

a.sum(2) is the sum of all slices along dim 2

a.sum(2)

[[ 10  35  60]
 [ 85 110 135]]

same as

a[:, :, 0] + \
a[:, :, 1] + \
a[:, :, 2] + \
a[:, :, 3] + \
a[:, :, 4]

[[ 10  35  60]
 [ 85 110 135]]

default axis is -1
this means all axes. or sum all numbers.

a.sum()

435
Answer from piRSquared on Stack Overflow
Top answer
1 of 3
95

Setup

consider the numpy array a

a = np.arange(30).reshape(2, 3, 5)
print(a)

[[[ 0  1  2  3  4]
  [ 5  6  7  8  9]
  [10 11 12 13 14]]

 [[15 16 17 18 19]
  [20 21 22 23 24]
  [25 26 27 28 29]]]

Where are the dimensions?

The dimensions and positions are highlighted by the following

            p  p  p  p  p
            o  o  o  o  o
            s  s  s  s  s

     dim 2  0  1  2  3  4

            |  |  |  |  |
  dim 0     โ†“  โ†“  โ†“  โ†“  โ†“
  ----> [[[ 0  1  2  3  4]   <---- dim 1, pos 0
  pos 0   [ 5  6  7  8  9]   <---- dim 1, pos 1
          [10 11 12 13 14]]  <---- dim 1, pos 2
  dim 0
  ---->  [[15 16 17 18 19]   <---- dim 1, pos 0
  pos 1   [20 21 22 23 24]   <---- dim 1, pos 1
          [25 26 27 28 29]]] <---- dim 1, pos 2
            โ†‘  โ†‘  โ†‘  โ†‘  โ†‘
            |  |  |  |  |

     dim 2  p  p  p  p  p
            o  o  o  o  o
            s  s  s  s  s

            0  1  2  3  4

Dimension examples:

This becomes more clear with a few examples

a[0, :, :] # dim 0, pos 0

[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]

a[:, 1, :] # dim 1, pos 1

[[ 5  6  7  8  9]
 [20 21 22 23 24]]

a[:, :, 3] # dim 2, pos 3

[[ 3  8 13]
 [18 23 28]]

sum

explanation of sum and axis
a.sum(0) is the sum of all slices along dim 0

a.sum(0)

[[15 17 19 21 23]
 [25 27 29 31 33]
 [35 37 39 41 43]]

same as

a[0, :, :] + \
a[1, :, :]

[[15 17 19 21 23]
 [25 27 29 31 33]
 [35 37 39 41 43]]

a.sum(1) is the sum of all slices along dim 1

a.sum(1)

[[15 18 21 24 27]
 [60 63 66 69 72]]

same as

a[:, 0, :] + \
a[:, 1, :] + \
a[:, 2, :]

[[15 18 21 24 27]
 [60 63 66 69 72]]

a.sum(2) is the sum of all slices along dim 2

a.sum(2)

[[ 10  35  60]
 [ 85 110 135]]

same as

a[:, :, 0] + \
a[:, :, 1] + \
a[:, :, 2] + \
a[:, :, 3] + \
a[:, :, 4]

[[ 10  35  60]
 [ 85 110 135]]

default axis is -1
this means all axes. or sum all numbers.

a.sum()

435
2 of 3
4

I use a nested loop operation to explain it.

import numpy as np

n = np.array(
[[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]],

 [[2, 4, 6],
 [8, 10, 12],
 [14, 16, 18]],

 [[1, 3, 5],
 [7, 9, 11],
 [13, 15, 17]]])

print(n)

print("============ sum axis=None=============")

sum = 0
for i in range(3):
  for j in range(3): 
    for k in range(3):
      sum += n[k][i][j]
print(sum) # 216

print('------------------')
print(np.sum(n))  # 216
print("============ sum axis=0 =============") 
for i in range(3):
  for j in range(3):
    sum = 0
    for axis in range(3):
      sum += n[axis][i][j]
    print(sum,end=' ')
  print()

print('------------------')
print("sum[0][0] = %d" % (n[0][0][0] + n[1][0][0] + n[2][0][0]))
print("sum[1][1] = %d" % (n[0][1][1] + n[1][1][1] + n[2][1][1]))
print("sum[2][2] = %d" % (n[0][2][2] + n[1][2][2] + n[2][2][2]))
print('------------------')
print(np.sum(n, axis=0)) 
print("============ sum axis=1 =============") 
for i in range(3):
  for j in range(3):
    sum = 0
    for axis in range(3):
      sum += n[i][axis][j]
    print(sum,end=' ')
  print()
print('------------------')
print("sum[0][0] = %d" % (n[0][0][0] + n[0][1][0] + n[0][2][0]))
print("sum[1][1] = %d" % (n[1][0][1] + n[1][1][1] + n[1][2][1]))
print("sum[2][2] = %d" % (n[2][0][2] + n[2][1][2] + n[2][2][2]))
print('------------------')
print(np.sum(n, axis=1))  
print("============ sum axis=2 =============") 
for i in range(3):
  for j in range(3):
    sum = 0
    for axis in range(3):
      sum += n[i][j][axis]
    print(sum,end=' ')
  print()
print('------------------')
print("sum[0][0] = %d" % (n[0][0][0] + n[0][0][1] + n[0][0][2]))
print("sum[1][1] = %d" % (n[1][1][0] + n[1][1][1] + n[1][1][2]))
print("sum[2][2] = %d" % (n[2][2][0] + n[2][2][1] + n[2][2][2]))
print('------------------')
print(np.sum(n, axis=2))
print("============ sum axis=(0,1)) =============") 
for i in range(3):
  sum = 0
  for axis1 in range(3):   
    for axis2 in range(3):
      sum += n[axis1][axis2][i]
  print(sum,end=' ')

print()
print('------------------')
print("sum[1] = %d" % (n[0][0][1] + n[0][1][1] + n[0][2][1] +
              n[1][0][1] + n[1][1][1] + n[1][2][1] +
              n[2][0][1] + n[2][1][1] + n[2][2][1] ))
print('------------------')
print(np.sum(n, axis=(0,1)))

result๏ผš

[[[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]]

 [[ 2  4  6]
  [ 8 10 12]
  [14 16 18]]

 [[ 1  3  5]
  [ 7  9 11]
  [13 15 17]]]
============ sum axis=None=============
216
------------------
216
============ sum axis=0 =============
4 9 14 
19 24 29 
34 39 44 
------------------
sum[0][0] = 4
sum[1][1] = 24
sum[2][2] = 44
------------------
[[ 4  9 14]
 [19 24 29]
 [34 39 44]]
============ sum axis=1 =============
12 15 18 
24 30 36 
21 27 33 
------------------
sum[0][0] = 12
sum[1][1] = 30
sum[2][2] = 33
------------------
[[12 15 18]
 [24 30 36]
 [21 27 33]]
============ sum axis=2 =============
6 15 24 
12 30 48 
9 27 45 
------------------
sum[0][0] = 6
sum[1][1] = 30
sum[2][2] = 45
------------------
[[ 6 15 24]
 [12 30 48]
 [ 9 27 45]]
============ sum axis=(0,1)) =============
57 72 87 
------------------
sum[1] = 72
------------------
[57 72 87]
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ generated โ€บ numpy.sum.html
numpy.sum โ€” NumPy v2.5 Manual
Elements to sum. ... Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.3 โ€บ reference โ€บ generated โ€บ numpy.sum.html
numpy.sum โ€” NumPy v2.3 Manual
Elements to sum. ... Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ numpy axis confusion
r/learnpython on Reddit: NumPy Axis Confusion
December 19, 2024 -

Not terribly new to Python or programming in general, but I'm looking at some initial NumPy exercises for Introduction to Statistical Learning with Applications in Python and I'm rather confused about the axis parameter to some methods.

Here's the relevant supporting code from the ISLP Lab Notebook:

    rng = np.random.default_rng(3)
    X = rng.standard_normal((10, 3))
    
    # array([[ 0.22578661, -0.35263079, -0.28128742],
    #        [-0.66804635, -1.05515055, -0.39080098],
    #        [ 0.48194539, -0.23855361,  0.9577587 ],
    #        [-0.19980213,  0.02425957,  1.54582085],
    #        [ 0.54510552, -0.50522874, -0.18283897],
    #        [ 0.54052513,  1.93508803, -0.26962033],
    #        [-0.24355868,  1.0023136 , -0.88645994],
    #        [-0.29172023,  0.88253897,  0.58035002],
    #        [ 0.0915167 ,  0.67010435, -2.82816231],
    #        [ 1.02130682, -0.95964476, -1.66861984]])
    
    X.mean(axis=0)
    
    # array([ 0.15030588,  0.14030961, -0.34238602])

The accompanying MD text here says:

The np.mean(), np.var(), and np.std() functions can also be applied to the rows and columns of a matrix. To see this, we construct a matrix of random variables, and consider computing its row sums.

Since arrays are row-major ordered, the first axis, i.e. axis=0, refers to its rows. We pass this argument into the mean() method for the object X.

I know axis=0 is rows and axis=1 is columns (for this example, at least). Since the example is passing axis 0 (rows) to the mean method, I would expect an output array of length 10 that calculates the mean of 3 elements in each row.

But the example appears to be calculating the mean of 10 elements in each of 3 columns, given the output array of length 3.

Further, when I calculate the column mean using X.mean(axis=1), I get the result I expected for axis=0, so the outputs are being switched.

The NumPy documentation didn't provide any additional clarity.

Hoping someone can provide an explanation for what's going on here. Is there possibly a setting (perhaps embedded in the notebook, that I can't see) that allows axes to be switched, where rows are axis=1 and columns are axis=0?

Thanks in advance for any help!

Top answer
1 of 1
2
If you have the following: import numpy as np vec = np.array([1, 2, 3, 4]) row = np.array([[1, 2, 3, 4]]) col = np.array([[1], [2], [3], [4]]) mat = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) book = np.array([[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]], [[1.1, 2.1, 3.1, 4.1], [5.1, 6.1, 7.1, 8.1]], [[1.2, 2.2, 3.2, 4.2], [5.2, 6.2, 7.2, 8.2]]]) The shape tuples are: > vec.shape (4 columns, ) >row.shape (1 row, 4 columns) > col.shape (4 rows, 1 column) > mat.shape (2 rows, 4 columns) > book.shape (3 sheets, 2 rows, 4 columns) axis 0, is element at index 0 in the shape tuple. axis=0 is columns for a 1d array, rows for a 2d array, sheets for a 3d array and relates to the outer []. axis 1, is element at index 1 in the shape tuple. axis=1 is columns for a 2d array, rows for a 2d array. Instead of approaching the shape tuple from left to right, approach the shape tuple from right to left. The last element axis=-1 is always columns, axis=-2 is always rows, axis=-3 is always sheets and so on... If we look at mat and think of the axis parameter as the following arrows: axis=-1 โ†’ operates along column axis np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) axis=-2 โ†“ np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) An operation along axis=-1, operates along columns and therefore returns a column: > mat.sum(axis=-1, keepdims=True) array([[10], [26]]) An operation along axis=-2, operates along rows and therefore returns a row: mat.sum(axis=-2, keepdims=True) > array([[ 6, 8, 10, 12]]) I've put a bit more detail in this markdown tutorial here covering the axis parameter and dimensionality of ndarrays. GitHub: numpy library: axis, shape and negative index . I'm still working on this tutorial but the section that covers the axis parameter should be helpful if you need a bit more information.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ numpy โ€บ numpy_ufunc_summations.asp
NumPy ufuncs - Summations
import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([1, 2, 3]) newarr = np.sum([arr1, arr2]) print(newarr) Try it Yourself ยป ยท Returns: 12 ยท If you specify axis=1, NumPy will sum the numbers in each array.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python โ€บ numpy
NumPy: Meaning of the axis parameter (0, 1, -1) | note.nkmk.me
January 18, 2024 - # print(np.sum(a, axis=2)) # AxisError: axis 2 is out of bounds for array of dimension 2
๐ŸŒ
SciPy
docs.scipy.org โ€บ doc โ€บ numpy-1.9.1 โ€บ reference โ€บ generated โ€บ numpy.sum.html
numpy.sum โ€” NumPy v1.10 Manual
October 18, 2015 - Sum of array elements over a given axis. ... Equivalent method. ... Cumulative sum of array elements. ... Integration of array values using the composite trapezoidal rule. ... Arithmetic is modular when using integer types, and no error is raised on overflow. The sum of an empty array is the neutral element 0: ... >>> np.sum([0.5, 1.5]) 2.0 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32) 1 >>> np.sum([[0, 1], [0, 5]]) 6 >>> np.sum([[0, 1], [0, 5]], axis=0) array([0, 6]) >>> np.sum([[0, 1], [0, 5]], axis=1) array([1, 5])
Find elsewhere
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ numpy โ€บ methods โ€บ sum
NumPy sum() (With Examples)
The axis argument defines how we can find the sum of elements in a 2-D array. If axis = None, the array is flattened and the sum of the flattened array is returned. If axis = 0, the sum is calculated column-wise. If axis = 1, the sum is calculated row-wise. import numpy as np array = np.array([[10, ...
๐ŸŒ
pythontutorials
pythontutorials.net โ€บ blog โ€บ numpy-sum-along-axis
Mastering `numpy.sum` Along Axis: A Comprehensive Guide โ€” pythontutorials.net
When axis = 1, the sum is calculated row-wise. That is, for each row, the elements in all columns are added together. import numpy as np arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # Summing along axis 0 sum_axis_0_3d = np.sum(arr_3d, axis = 0) print("Sum along axis 0 in 3D array:", sum_axis_0_3d) # Summing along axis 1 sum_axis_1_3d = np.sum(arr_3d, axis = 1) print("Sum along axis 1 in 3D array:", sum_axis_1_3d) # Summing along axis 2 sum_axis_2_3d = np.sum(arr_3d, axis = 2) print("Sum along axis 2 in 3D array:", sum_axis_2_3d)
๐ŸŒ
Medium
medium.com โ€บ intuitionmath โ€บ numpy-sum-axis-intuition-6eb94926a5d1
Numpy Sum Axis Intuition
March 6, 2023 - Am I the only one who is wondering this? The way to understand what โ€œaxisโ€ means in numpy sum is that it collapses the specified axis. So when it collapses the axis 0 (the row), it becomes just one row (it sums column-wise).
๐ŸŒ
Centron
centron.de โ€บ home โ€บ tutorials โ€บ numpy.sum() in python - tutorial
numpy.sum() in Python - Tutorial โ€“ centron
March 1, 2024 - The array elements are used to calculate the sum. If the axis is not provided, the sum of all the elements is returned.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ numpy-sum-in-python
numpy.sum() in Python - GeeksforGeeks
August 28, 2024 - Otherwise, it will consider arr to be flattened(works on all the axes). axis = 0 means along the column and axis = 1 means working along the row. out: Different array in which we want to place the result. The array must have the same dimensions as the expected output. The default is None. initial : [scalar, optional] Starting value of the sum.
๐ŸŒ
Medium
medium.com โ€บ @weidagang โ€บ understanding-axes-in-numpy-8c889794e541
Understanding Axes in NumPy. Your Key to Array Manipulation | by Dagang Wei | Medium
May 28, 2024 - axis=2: Operates along columns within each depth level. The code is available in this colab notebook. import numpy as np # 1D Array arr_1d = np.array([1, 2, 3, 4]) print("1D Array:\n", arr_1d) # Output: [1 2 3 4] print("Sum (Axis 0):", ...
๐ŸŒ
SciPy
docs.scipy.org โ€บ doc โ€บ numpy-1.15.1 โ€บ reference โ€บ generated โ€บ numpy.sum.html
numpy.sum โ€” NumPy v1.15 Manual
August 23, 2018 - Sum of array elements over a given axis. ... Equivalent method. ... Cumulative sum of array elements. ... Integration of array values using the composite trapezoidal rule. ... Arithmetic is modular when using integer types, and no error is raised on overflow. The sum of an empty array is the neutral element 0: ... >>> np.sum([0.5, 1.5]) 2.0 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32) 1 >>> np.sum([[0, 1], [0, 5]]) 6 >>> np.sum([[0, 1], [0, 5]], axis=0) array([0, 6]) >>> np.sum([[0, 1], [0, 5]], axis=1) array([1, 5])
๐ŸŒ
Jiffyclub
jiffyclub.github.io โ€บ numpy โ€บ reference โ€บ generated โ€บ numpy.sum.html
numpy.sum โ€” NumPy v1.12 Manual
Sum of array elements over a given axis. ... Equivalent method. ... Cumulative sum of array elements. ... Integration of array values using the composite trapezoidal rule. ... Arithmetic is modular when using integer types, and no error is raised on overflow. The sum of an empty array is the neutral element 0: ... >>> np.sum([0.5, 1.5]) 2.0 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32) 1 >>> np.sum([[0, 1], [0, 5]]) 6 >>> np.sum([[0, 1], [0, 5]], axis=0) array([0, 6]) >>> np.sum([[0, 1], [0, 5]], axis=1) array([1, 5])
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.1 โ€บ reference โ€บ generated โ€บ numpy.sum.html
numpy.sum โ€” NumPy v2.1 Manual
Elements to sum. ... Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array.
๐ŸŒ
Medium
medium.com โ€บ data-science โ€บ understanding-numpy-sum-1587eec69527
Understanding NumPy sum. If you are not clear on what NumPy isโ€ฆ | by Kshitij Bajracharya | TDS Archive | Medium
August 20, 2018 - This is exactly what we get when we do three_d_array.sum(axis=1); performing element by element addition along axis=1. Again, the shape of the sum matrix is (4,2), which shows that we got rid of the second axis 3 from the original (4,3,2).
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.1 โ€บ reference โ€บ generated โ€บ numpy.matrix.sum.html
numpy.matrix.sum โ€” NumPy v2.1 Manual
Returns the sum of the matrix elements, along the given axis. Refer to numpy.sum for full documentation. ... This is the same as ndarray.sum, except that where an ndarray would be returned, a matrix object is returned instead. ... >>> x = np.matrix([[1, 2], [4, 3]]) >>> x.sum() 10 >>> x.sum(axis=1) ...
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.2 โ€บ reference โ€บ generated โ€บ numpy.matrix.sum.html
numpy.matrix.sum โ€” NumPy v2.2 Manual
Returns the sum of the matrix elements, along the given axis. Refer to numpy.sum for full documentation. ... This is the same as ndarray.sum, except that where an ndarray would be returned, a matrix object is returned instead. ... >>> x = np.matrix([[1, 2], [4, 3]]) >>> x.sum() 10 >>> x.sum(axis=1) ...