Can numpy vector function use buffer as output?
Can I get a numeric vectorized function to use the buffer object as the result, rather than create a new array returned by that object?
I would like to do something like this:
fun = numpy.vectorize(lambda x: x + 1) a = numpy.zeros((1, 10) buf = numpy.zeros((1, 10) fun(a, buf_obj = buf)
Unlike
fun = numpy.vectorize(lambda x: x + 1)
a = numpy.zeros((1, 10)
buf = fun(a)
source to share
Not for vectorize
, but most numpy functions take an argument out
that does exactly what you want.
What function are you trying to use numpy.vectorize
with? vectorize
is almost always the wrong decision when trying to "vectorize" a computation.
In the example above, if you want to perform an operation in place, you can accomplish it with:
a = numpy.zeros((1, 10)) a += 1
Or, if you want to be a little verbose, but do exactly what your example will do:
a = numpy.zeros((1, 10)) buf = numpy.empty_like(a) numpy.add(a, 1, out=buf)
numpy.vectorize
should call python function on every element of the array. Therefore, it has additional overhead compared to numpy functions that work on the entire array. Usually, when people refer to "vectorizing" an expression to get a speedup, they are referring to building the expression out of the building blocks of basic numpy functions, not using it vectorize
(which is certainly confusing ...).
Edit: Based on your comment, vectorize
really fits your use case! (Writing a "raster calculator" is a pretty handy option for him, apart from security / sandbox issues.)
On the other hand, numexpr
it is probably even better suited if you don't mind the additional dependency.
It's faster and takes a parameter out
.
source to share