Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (47.6k points)

What is the most efficient way to map a function over a numpy array? The way I've been doing it in my current project is as follows:

import numpy as np 

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

# Obtain array of square of each element in x 

squarer = lambda t: t ** 2 

squares = np.array([squarer(xi) for xi in x])

However, this seems like it is probably very inefficient since I am using a list comprehension to construct the new array as a Python list before converting it back to a numpy array.

Can we do better?

1 Answer

0 votes
by (106k points)

The most efficient way to map a function over the numpy array is to use the numpy.vectorize method:-

import numpy as np 

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

squarer = lambda t: t ** 2 

vfunc = np.vectorize(squarer) 

vfunc(x)

Related questions

0 votes
1 answer
asked Aug 5, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
3 answers
asked Sep 20, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...