Categories: NumpyPython

Using apply_along_axis() to apply an aggregate function upon an Numpy array in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental level, click here for more details.

As an alternative to for looping, Numpy provides an aggregate function, apply_along_axis(), that applies various summary functions upon an array’s column or rows. The function has an option paraemter ‘axis’, which stands for columns when it equals to 0 and for rows when it is 1. In addition to functions that come from Python installation, user-written functions can be applied with apply_along_axis() as well. The following example shows usage of the function.

#Import Numpy module
import numpy as np
#create a two-dimensioanl Numpy array of shape (4,3)
W = np.arange(22, 34).reshape((4, 3))
W
#output
array([[22, 23, 24],
       [25, 26, 27],
       [28, 29, 30],
       [31, 32, 33]])
#calculate mean of the array, by columns
np.apply_along_axis(np.mean, axis=0, arr=W)
#result
array([26.5, 27.5, 28.5])
#calculate mean of the array, by rows
np.apply_along_axis(np.mean, axis=1, arr=W)
#result
array([23., 26., 29., 32.])
#define a user-written function, calculating squares 
def square(z):
    return z * z
#apply square to the array, calculate squares by rows
np.apply_along_axis(square, axis=1, arr=W)
# results
array([[ 484,  529,  576],
       [ 625,  676,  729],
       [ 784,  841,  900],
       [ 961, 1024, 1089]])
#apply square to the array, calculate squares by rows
np.apply_along_axis(square, axis=0, arr=W)
#result
array([[ 484,  529,  576],
       [ 625,  676,  729],
       [ 784,  841,  900],
       [ 961, 1024, 1089]])

As we can see, the shape of the results depends on the input array and the specific functions applying on it.

You can also watch videos on our YouTube channel for more understanding of Python programming skills.

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago