Consider the following code:
import numpy as np
a = np.zeros(50)
a[10:20:2] = 1
b = c = a[10:40:4]
print b.flags # You'll see that b and c are not C_CONTIGUOUS or F_CONTIGUOUS
My question:
Is there a way (with only a reference to b
) to make both b
and c
contiguous?
It is completely fine if np.may_share_memory(b,a)
returns False
after this operation.
Things which are close, but don't quite work out are: np.ascontiguousarray
/np.asfortranarray
as they will return a new array.
My use case is that I have very large 3D fields stored in a subclass of a numpy.ndarray
. In order to save memory, I would like to chop those fields down to the portion of the domain that I am actually interested in processing:
a = a[ix1:ix2,iy1:iy2,iz1:iz2]
Slicing for the subclass is somewhat more restricted than slicing of ndarray
objects, but this should work and it will "do the right thing" -- the various custom meta-data attached on the subclass will be transformed/preserved as expected. Unfortunately, since this returns a view
, numpy won't free the big array afterward so I don't actually save any memory here.
To be completely clear, I'm looking to accomplish 2 things:
- preserve the metadata on my class instance. slicing will work, but I'm not sure about other forms of copying.
- make it so that the original array is free to be garbage collected