Is it possible to map a NumPy array in place? If yes, how?
Given a_values – 2D array – this is the bit of code that does the trick for me at the moment:
for row in range(len(a_values)):
for col in range(len(a_values[0])):
a_values[row][col] = dim(a_values[row][col])
But it’s so ugly that I suspect that somewhere within NumPy there must be a function that does the same with something looking like:
a_values.map_in_place(dim)
but if something like the above exists, I’ve been unable to find it.
It’s only worth trying to do this in-place if you are under significant space constraints. If that’s the case, it is possible to speed up your code a little bit by iterating over a flattened view of the array. Since
reshapereturns a new view when possible, the data itself isn’t copied (unless the original has unusual structure).I don’t know of a better way to achieve bona fide in-place application of an arbitrary Python function.
Some timings:
It’s about twice as fast as the nested loop version:
Of course vectorize is still faster, so if you can make a copy, use that:
And if you can rewrite
dimusing built-in ufuncs, then please, please, don’tvectorize:numpydoes operations like+=in place, just as you might expect — so you can get the speed of a ufunc with in-place application at no cost. Sometimes it’s even faster! See here for an example.By the way, my original answer to this question, which can be viewed in its edit history, is ridiculous, and involved vectorizing over indices into
a. Not only did it have to do some funky stuff to bypassvectorize‘s type-detection mechanism, it turned out to be just as slow as the nested loop version. So much for cleverness!