I have been learning NumPy basics, I kind of love how they leverage the combination of the ability to have native libraries and data types with operator overloading to work around some of CPython's greatest limitations by utilizing its greatest strengths.
Intros to NumPy (and I have watched several now) all seem to pretend that the n-dimensional array manipulation functions .reshape(), .transpose() and .ravel() always return a view.
Looking at the docs, they suggest that under certain conditions this is not possible, and you would actually get a new copy of the data.
To me, this is an important distinction for several reasons, it is important for me to know at all times whether I am working on a copy of data or messing with the original data.
That a substantial number of people seem to think they always simply return views suggests to me that the conditions under which you do not receive a new view of the same data are somewhat rare.
But for the life of me, I can't figure out when that is.
Can someone tell me when .reshape(), .ravel() or .transpose() are unable to return views and so yield independent copies of the data?
I think it has something to do about having changed the order during the lifetime of the array, the quotes from the help for .reshape() hint vaguely at this to me but I am not coming up with some easy rule to say when these functions will return a copy instead of a view:
It is not always possible to change the shape of an array without
copying the data. If you want an error to be raised when the data is copied,
you should assign the new shape to the shape attribute of the array::
>>> a = np.zeros((10, 2))
# A transpose makes the array non-contiguous
>>> b = a.T
# Taking a view makes it possible to modify the shape without modifying
# the initial object.
>>> c = b.view()
>>> c.shape = (20)
Traceback (most recent call last):
AttributeError: Incompatible shape for in-place modification. Use
`.reshape()` to make a copy with the desired shape.
You showed up just in time for the waffles! And this tiny ad: