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

what are Transformer, LLM , and GPT

In the field of AI and Natural Language Processing (NLP), The Transformer is the engine…

1 day ago

Main framework for PyTorch music generation model

If your goal is purely symbolic melody generation (e.g., generating MIDI files or notes rather…

4 days ago

affine_grid() in pytorch

According to PyTorch document, In PyTorch, torch.nn.functional.affine_grid generates a 2D or 3D flow field (sampling…

2 months ago

How to create an Android mobile app with a deep learning AI model ?

Creating an Android mobile app with a deep learning AI model involves several key steps:…

11 months ago

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

1 year ago

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

1 year ago