How can I find out if NumPy is creating a view or copy?

For a minimal working example, digitize a 2D array. numpy.digitize requires a 1D array:

 import numpy as np N = 200 A = np.random.random((N, N)) X = np.linspace(0, 1, 20) print np.digitize(A.ravel(), X).reshape((N, N)) 

Now the documentation :

... A copy is made only if necessary.

How do I know if a ravel copy is needed in this case? In general - is there a way that I can determine if a particular operation creates a copy or view?

+56
python numpy copy
Jul 17 2018-12-12T00:
source share
2 answers

This question is very similar to the question I asked a while ago:

You can check the base attribute.

 a = np.arange(50) b = a.reshape((5, 10)) print (b.base is a) 

However, this is not ideal. You can also check if they are using memory with np.may_share_memory .

 print (np.may_share_memory(a, b)) 

There is also a flags attribute that you can check:

 print (b.flags['OWNDATA']) #False -- apparently this is a view e = np.ravel(b[:, 2]) print (e.flags['OWNDATA']) #True -- Apparently this is a new numpy object. 

But this last one seems a little suspicious to me, although I can’t say why ...

+64
Jul 17 '12 at 14:30
source share

The documentation for reshape has information on how to provide an exception if the presentation cannot be executed:

It is not possible to change the shape of an array without copying data. If you want the error to be raised if the data was copied, you must assign a new shape to the shape attribute of the array:

 >>> a = np.zeros((10, 2)) # A transpose make the array non-contiguous >>> b = aT # Taking a view makes it possible to modify the shape without modiying the # initial object. >>> c = b.view() >>> c.shape = (20) AttributeError: incompatible shape for a non-contiguous array 




This is not exactly the answer to your question, but in some cases it can be just as useful.

+17
Jan 11 '13 at 3:40
source share



All Articles