splinter splinter -3 years ago 102
Python Question

Efficiently using Numpy to assign function values to array

I am interested in finding the fastest way of carrying a simple operation in Python3.6 using Numpy. I wish to create a function and from a given array to an array of function values. Here is a simplified code that does that using


import numpy as np
def func(x):
return x**2
xRange = np.arange(0,1,0.01)
arr_func = np.array(list(map(func, xRange)))

However, as I am running it with a complicated function and using large arrays, runtime speed is very important for me. Is there a known faster way?

EDIT My question is not the same as this one, because I am asking about assigning from a function, as opposed to a generator.

Answer Source

Check the related How do I build a numpy array from a generator?, where the most compelling option seems to be preallocating the numpy array and setting values, instead of creating a throwaway intermediate list.

arr_func = np.empty(len(xRange))
for i in range(len(xRange)):
  arr_func[i] = func(xRange[i])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download