How to calculate the sum along an axis with numpy in python ?

Published: September 19, 2021

Tags: Python; Numpy;

DMCA.com Protection Status

Examples of how to calculate the sum along an axis with numpy in python:

Create a random matrix with numpy

Let's create a random matrix with numpy of size = (3,3):

import numpy as np

data = np.random.randint(0,5,size=(3,3))

returns for example

array([[4, 1, 2],
             [2, 1, 1],
             [4, 0, 1]])

Sum along the first axis (axis=0)

To sum along a given axis of a matrix with numpy, a solution is to use numpy.sum with the parameter "axis":

data.sum(axis=0)

gives

array([10,  2,  4])

Sum along the second axis (axis=1)

Another example along the axis=1

data.sum(axis=1)

gives

array([7, 4, 5])

Sum all elements of a matrix with numpy

Note: to sum all elements of a matrix with numpy:

data.sum()

gives here

16

Another example with more than 2 dimensions

Another example with a matrix of size = (3,3,3)

import numpy as np

data = np.random.randint(0,5,size=(3,3,3))

gives gor example

array([[[4, 2, 4],
        [3, 3, 1],
        [0, 4, 1]],

       [[3, 4, 0],
        [3, 1, 3],
        [4, 4, 2]],

       [[2, 0, 2],
        [2, 4, 1],
        [3, 3, 4]]])

Sum along axis=0

data.sum(axis=0)

gives

array([[ 9,  6,  6],
             [ 8,  8,  5],
             [ 7, 11,  7]])

Sum along axis=1

data.sum(axis=1)

gives

array([[ 7,  9,  6],
       [10,  9,  5],
       [ 7,  7,  7]])

Sum along axis=2

data.sum(axis=2)

gives

array([[10,  7,  5],
       [ 7,  7, 10],
       [ 4,  7, 10]])

References