[Numpy-discussion] Checking for views (was: Should arr.diagonal() return a copy or aview?)

josef.pktd at gmail.com josef.pktd at gmail.com
Thu May 24 15:20:12 EDT 2012

On Thu, May 24, 2012 at 1:59 PM, Nathaniel Smith <njs at pobox.com> wrote:
> On Thu, May 24, 2012 at 6:07 PM, Larsen, Brian A <balarsen at lanl.gov> wrote:
>> This is the stack overflow discussion mentioned.
>> http://stackoverflow.com/questions/9164269/can-you-tell-if-an-array-is-a-view-of-another
>> I basically implemented the answer from SO.  I feel like the "is" gives you
>> a good handle on things since to be true they are actually the same location
>> in memory.
> If using the current development version of numpy, that answer is
> actually wrong... if you do
>  a = np.arange(10)
>  b = a.view()
>  c = b.view()
> then in the development version, c.base is a, not b. This is the
> source of some contention and confusion right now...:
>  https://github.com/numpy/numpy/pull/280#issuecomment-5888154
> In any case, if "b.base is a" is True, then you can be pretty certain
> that b and a share memory, but if it is False, it doesn't tell you
> much at all. AFAICT np.may_share_memory would be strictly more useful.

as example:

I checked pandas recently and IIRC, I needed three .base to get a True

>>> x = np.random.randn(4,5)
>>> xdf = pa.DataFrame(data=x)
>>> type(xdf[1])
<class 'pandas.core.series.Series'>
>>> xdf[1].base is x
>>> xdf[1].base.base is x
>>> xdf[1].base.base.base is x
>>> np.may_share_memory(xdf[1], x)


> -- Nathaniel
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion

More information about the NumPy-Discussion mailing list