How to apply a function to the values of a column array using numpy ?

There are various methods to use numpy and apply a function to the values of a column array. Examples:

Apply a custom function to a sliced numpy array

We have an array called here data

import numpy as np

data = np.arange(30).reshape((10,3))

print(data)

gives

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]
 [12 13 14]
 [15 16 17]
 [18 19 20]
 [21 22 23]
 [24 25 26]
 [27 28 29]]

and we need to apply a custom function for example

def myFunc(X):
    slope = 2.0
    intercept = -4.0
    return slope * X + intercept

specifically to the second column. To do that a a solution is to slice the array first data[:,1] and to apply our function:

myFunc(data[:,1])

Output

array([-2.,  4., 10., 16., 22., 28., 34., 40., 46., 52.])

To modify the data array directly:

data[:,1] =  myFunc(data[:,1])

Output

[[ 0 -2  2]
 [ 3  4  5]
 [ 6 10  8]
 [ 9 16 11]
 [12 22 14]
 [15 28 17]
 [18 34 20]
 [21 40 23]
 [24 46 26]
 [27 52 29]]

Using numpy function apply_along_axis()

Another solution is to using the numpy.apply_along_axis() method, which takes in three parameters:

  • A user-defined function,

  • An axis index (0 for row and 1 for column), and

  • The array from which the function needs to be applied.

The method returns a new array, after applying the specified function along all elements of the array based on the axis index given.

np.apply_along_axis(myFunc,1,data)

Output

array([[-4., -2.,  0.],
       [ 2.,  4.,  6.],
       [ 8., 10., 12.],
       [14., 16., 18.],
       [20., 22., 24.],
       [26., 28., 30.],
       [32., 34., 36.],
       [38., 40., 42.],
       [44., 46., 48.],
       [50., 52., 54.]])

To apply a function to a specific column, same

np.apply_along_axis(myFunc,0,data[:,1])

Output

array([-2.,  4., 10., 16., 22., 28., 34., 40., 46., 52.])

References

Links Site
Array creation numpy.org
numpy.apply_along_axis numpy.org