Home > Software design >  is there a numpy function that equivalent to python map
is there a numpy function that equivalent to python map

Time:04-19

i have a 3d array that contains n 2d arrays is there anyway that i can map each 2d array to some value with out using the bulit in python map or for loops (i have been asked to do with out it) only with numpy functions.

for example i want to do something like that:

def map2d_arr(arr2d): #this is for the exampe only can be any condition on the 2d array
    return sum(arr2d) > 10;

a = np.arange(27).reshape((3,3,3))
res = np.map(map2d_arr,a) # how to do something like that only in numpy
                          #should return boolean array 

there is np.vectorize and along axis but they dont take full 2d arrays

CodePudding user response:

No, but you can easily make a lambda function to serve that purpose.


list = np.array([1, 2, 3, 4])

#define function
my_function = lambda x: x*2

#apply function to NumPy array
my_function(list)

#Result : list = [2, 4, 6, 8]

Hope this helped!

CodePudding user response:

Let's drop the boolean test, and just use sum - it clarifies the dimensional action:

In [130]: a = np.arange(27).reshape((3,3,3))

You apparently want to apply sum to each of the 2d arrays, iterating on the first dimension.

In [131]: sum(a[0])
Out[131]: array([ 9, 12, 15])

Effectively a[0][0] a[0][1] a[0][2].

For this the python map works just fine:

In [132]: list(map(sum, a))
Out[132]: [array([ 9, 12, 15]), array([36, 39, 42]), array([63, 66, 69])]

Equivalently in list comprehension form:

In [133]: [sum(i) for i in a]
Out[133]: [array([ 9, 12, 15]), array([36, 39, 42]), array([63, 66, 69])]

Or using vectorize with signature:

In [134]: f = np.vectorize(sum, signature='(n,m)->(m)')
In [135]: f(a)
Out[135]: 
array([[ 9, 12, 15],
       [36, 39, 42],
       [63, 66, 69]])

but we can do the same with np.sum:

In [136]: np.sum(a, axis=1)
Out[136]: 
array([[ 9, 12, 15],
       [36, 39, 42],
       [63, 66, 69]])

[136] is, by far the fastest. vectorize is slower than list comprehension for small cases, but scales better. vectorize with signature is generally slower (but that needs to be tested). map and list comprehension are about the same.

apply_along_axis is generally slower, though it can simplify nested iterations. I don't recommend it for 2d cases, where list comprehension is clean enough and faster.

  • Related