Reputation: 10573
Let's say I have an numpy array
import numpy as np
a = np.array([[1,2,3],[3,4,5]])
and I defined a function to process the data, e.g, get the product of a vector:
def vp(v):
p = 1
for i in v:
p = p * i
return p
and how can I easily broadcast the function to all the vectors in a by something like the map function for the list, e.g. vp(a)
will give me [6, 60]
?
what if a is a 3D or even 4D array, is there a good way to broadcast such customized function?
Upvotes: 0
Views: 84
Reputation: 7806
I think the core of your question relies on creating custom functions to apply over multidimensional datasets. For that you would use numpy.apply_along_axis().
a = array([[1, 2, 3],
[3, 4, 5]])
np.apply_along_axis(arr = a, func1d=vp, axis=1)
> array([ 6, 60])
Yes this also works with N-Dimentional datasets.
c = array([[[ 1, 2],
[ 3, 3],
[ 4, 5]],
[[16, 17],
[18, 18],
[19, 20]]])
np.apply_along_axis(vp, axis=1, arr=c)
> array([[ 12, 30],
[5472, 6120]])
Upvotes: 1