[Numpy-discussion] Best way to construct/slice 3-dimensional ndarray from multiple 2d ndarrays?

Aronne Merrelli aronne.merrelli@gmail....
Wed Aug 17 12:46:12 CDT 2011


On Wed, Aug 17, 2011 at 9:04 AM, Keith Hughitt <keith.hughitt@gmail.com>wrote:

>
> Also, when subclassing ndarray and calling obj = data.view(cls) for an
> ndarray "data", does this copy the data into the new object by value or
> reference? The method which extracts the 2d slice actually returns a
> subclass of ndarray created using the extracted data, so this is why I ask.
>
>
>
I think it should pass a reference - the following code suggests the
subclass is sharing the same fundamental array object. You can use the .base
attribute of the ndarray object to see if it is a view back to another
ndarray object:

import numpy as np
class TestClass(np.ndarray):
    def __new__(cls, inp_array):
        return inp_array.view(cls)

In [2]: x = np.ones(5)
In [3]: obj = TestClass(x)
In [4]: id(x), id(obj), id(obj.base)
Out[4]: (23517648, 19708080, 23517648)
In [5]: print x, obj
[ 1.  1.  1.  1.  1.] [ 1.  1.  1.  1.  1.]
In [6]: x[2] = 2
In [7]: print x, obj
[ 1.  1.  2.  1.  1.] [ 1.  1.  2.  1.  1.]


If you change the TestClass.__new__() to: "return
np.array(inp_array).view(cls)" then you will make a copy of the input array
instead, if that is needed. In that case, it looks like the .base attribute
is a new ndarray, copied from the input array.


Aronne

[PS - also note that .base is set to None, if the ndarray is not a view into
another ndarray; it turns out that None has a valid object number, which
confused me at first - see id(None).]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20110817/4f4825ad/attachment.html 


More information about the NumPy-Discussion mailing list