All above answers compares well, but if you need to use custom function for mapping, and you have numpy.ndarray
, and you need to retain the shape of array.
I have compare just two, but it will retain the shape of ndarray
. I have used the array with 1 million entries for comparison. Here I use square function. I am presenting the general case for n dimensional array. For two dimensional just make iter
for 2D.
import numpy, time
def A(e):
return e * e
def timeit():
y = numpy.arange(1000000)
now = time.time()
numpy.array([A(x) for x in y.reshape(-1)]).reshape(y.shape)
print(time.time() - now)
now = time.time()
numpy.fromiter((A(x) for x in y.reshape(-1)), y.dtype).reshape(y.shape)
print(time.time() - now)
now = time.time()
numpy.square(y)
print(time.time() - now)
Output
>>> timeit()
1.162431240081787 # list comprehension and then building numpy array
1.0775556564331055 # from numpy.fromiter
0.002948284149169922 # using inbuilt function
here you can clearly see numpy.fromiter
user square function, use any of your choice. If you function is dependent on i, j
that is indices of array, iterate on size of array like for ind in range(arr.size)
, use numpy.unravel_index
to get i, j, ..
based on your 1D index and shape of array numpy.unravel_index
This answers is inspired by my answer on other question here