Vectorize
It is used to create a vectorize function on the numpy array.
Basic syntax
np.vectorize(user_def_fn)
It returns a vectorize function which access numpy array. Numpy then maps the array elements over the function.
nums = np.arange(10)
square = np.vectorize(lambda x: x * x)
square(nums)
# array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81])
signature
By default function gets scaler value from the array and returns the scaler value as output. However, we can change this behavior using optional parameter signature
.
A signature specifies what nd
array the function would accept and returns as output.
nums = np.arange(4).reshape((2, 2))
# array([[0, 1],
# [2, 3]])
square_array = np.vectorize(lambda sub_array: sub_array ** 2, signature="(n)->(n)")
square_array(nums)
Signature (n) -> (n)
specifies that the function would take 1d array as input and returns 1d array as output. Signature specifies the shape of input and output array.
(n, k) -> (n)
means the function takes 2d array as input and returns 1d array as output. If the function returns 2d array as output, the signature should be (n, k) -> (x, y)
.
Note:
The variables used in input and output signature has not to be same by names.
Signature (n),(n)->(),()
specifies that the vectorized function takes two 1d arrays and return two scaler values