How can I tell if NumPy creates a view or a copy?

This question is very similar to a question that I asked a while back:

You can check the base attribute.

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

However, that’s not perfect. You can also check to see if they share memory using np.may_share_memory.

print (np.may_share_memory(a, b))

There’s also the 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 fishy to me, although I can’t quite put my finger on why…

Leave a Comment