Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Python
  3. Question
Python

Most efficient way to map function over NumPy array

Asked by Ajith Jayaraman Apr 6, 2021 653 views 1 answer
Share

About this question

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?


Your answer

1 Answer

More Python discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Python Blogs

Guides, tips and career advice on Python from JanBask experts.