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.
0 Comments