[Numpy-discussion] Best way to construct/slice 3-dimensional ndarray from multiple 2d ndarrays?
Keith Hughitt
keith.hughitt@gmail....
Wed Aug 17 13:11:33 CDT 2011
Great! It looks like it is in fact working as desired:
In [4]: cube.shape
Out[4]: (5, 4096, 4096)
In [5]: slice = cube[0]
In [6]: cube[0,1000,1000]
Out[6]: 618
In [7]: slice[1000,1000]
Out[7]: 618
In [8]: slice[1000,1000] = 123
In [9]: cube[0, 1000,1000]
Out[9]: 123
I didn't know about the .base attribute; that is really useful.
Thank you both for the feedback.
Keith
On Wed, Aug 17, 2011 at 1:46 PM, Aronne Merrelli
<aronne.merrelli@gmail.com>wrote:
>
>
> 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).]
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20110817/9f826a7f/attachment.html
More information about the NumPy-Discussion
mailing list