[Numpy-discussion] a.flat[3:7] is a copy?

Matthieu Brucher matthieu.brucher at gmail.com
Sun Jul 29 05:38:04 EDT 2007


Hi,

Did you try ravel() instead ? If a copy is not needed, it returns a 1D view
of the array.

Matthieu

2007/7/18, Tom Goddard <goddard at cgl.ucsf.edu>:
>
> Does taking a slice of a flatiter always make a copy?  That appears to
> be the behaviour in numpy 1.0.3.
> For example a.flat[1:3][0] = 5 does not modify the original array a,
> even when a is contiguous.  Is this a bug?
>
> >>> import numpy as n
> >>> n.version.version
> '1.0.3'
> >>> a = n.zeros((2,3), n.int32)
> >>> a
> array([[0, 0, 0],
>        [0, 0, 0]])
> >>> b = a.flat[1:3]
> >>> b[0] = 5
> >>> b
> array([5, 0])
> >>> a
> array([[0, 0, 0],
>        [0, 0, 0]])
> >>> b = None
> >>> a
> array([[0, 0, 0],
>        [0, 0, 0]])
>
> This behavior does not seem to match what is described in the Numpy book
> (Dec 7, 2006 version), section 3.1.3 "Other attributes", page 51:
>
> "flat
>
>   Returns an iterator object (numpy.flatiter) that acts like a 1-d
> version of the array.
>   1-d indexing works on this array and it can be passed in to most
> routines as
>   an array wherein a 1-d array will be constructed from it.  The new 1-d
> array
>   will reference this array's data if this array is C-style contiguous,
> otherwise,
>   new memory will be allocated for the 1-d array, the UPDATEIFCOPY flag
>   will be set for the new array, and this array will have its WRITEABLE
> flag
>   set FALSE until the the last reference to the new array disappears.
> When the
>   last reference to the new 1-d array disappears, the data will be
> copied over to
>   this non-contiguous array.  This is done so that a.flat effectively
> references the
>   current array regardless of whether or not it is contiguous or
> non-contiguous."
>
> Tom Goddard
> UC San Francisco
>
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20070729/a3920186/attachment.html>


More information about the NumPy-Discussion mailing list