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

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

6 days ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

2 weeks ago

Topic Modeling using Latent Dirichlet Allocation with Python

Topic modeling is a subcategory of unsupervised machine learning method, and a clustering task in…

1 month ago

Document sentiment classification using bag-of-words in Python

For online Python training registration, click here ! Sentiment classification is a type of machine…

2 months ago

Download R Course source files

Click here to download R Course source files !

10 months ago

Download Python Course source files

Click here to download Python Course Source Files !

10 months ago