Reputation: 326
This question has info on using an input as an output to compute something in place with a numpy.ufunc
:
Is it possible to avoid allocating space for an unwanted output of a numpy.ufunc
? For example, say I only want one of the two outputs from modf
. Can I ensure that the other, unwanted array is never allocated at all?
I thought passing _
to out
might do it, but it throws an error:
import numpy as np
ar = np.arange(6)/3
np.modf(ar, out=(ar, _))
TypeError: return arrays must be of ArrayType
As it says in the docs, passing None
means that the output array is allocated in the function and returned. I can ignore the returned values, but it still has to be allocated and populated inside the function.
Upvotes: 2
Views: 287
Reputation: 1740
You can minimize allocation by passing a "fake" array:
ar = np.arange(6) / 3
np.modf(ar, ar, np.broadcast_arrays(ar.dtype.type(0), ar)[0])
This dummy array is as big as a single double
, and modf
will not do allocation internally.
EDIT According to suggestions from @Eric and @hpaulj, a more general and long-term solution would be
np.lib.stride_tricks._broadcast_to(np.empty(1, ar.dtype), ar.shape, False, False)
Upvotes: 4