[Numpy-discussion] Downcasting an array in-place?

Joe Kington jkington at wisc.edu
Tue May 11 12:15:56 EDT 2010


Is it possible to downcast an array in-place?

For example:
x = np.random.random(10) # Placeholder for "real" data
x -= x.min()
x /= x.ptp() / 255
x = x.astype(np.uint8)  <-- returns a copy

First off, a bit of background to the question... At the moment, I'm trying
to downcast a large (>10GB) array of uint16's to uint8's. I have enough RAM
to fit everything into memory, but I'd really prefer to use as few copies as
possible....

In the particular case of a C-ordered uint16 array to uint8 on a
little-endian system, I can do this:
# "x" is the big 3D array of uint16's
x -= x.min()
x /= x.ptp() / 255
x = x.view(np.uint8)[:, :, ::2]

That works, but a)  produces a non-contiguous array, and b)  is awfully
case-specific.

Is there a way to do something similar to astype(), but have it
"cannibalize" the memory of the original array?  (e.g. the "out" argument in
a ufunc?)

Hopefully my question makes some sense to someone other than myself...

Thanks!
-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20100511/08fb8b29/attachment.html>


More information about the NumPy-Discussion mailing list