[Numpy-discussion] views or copy

Robert Kern robert.kern@gmail....
Mon Apr 6 22:34:45 CDT 2009


On Mon, Apr 6, 2009 at 22:31,  <josef.pktd@gmail.com> wrote:
> I ran again into a problem where numpy created a view (which I didn't
> realize) and an operation works differently on the view than if it
> were a copy.
>
> I try to construct an example array, which, however, is only a view
>
>>>> x,y = np.mgrid[0:3,0:3]
>>>> xx = np.vstack((x.flatten(), y.flatten(), np.ones(9))).T
>>>> xx
> array([[ 0.,  0.,  1.],
>       [ 0.,  1.,  1.],
>       [ 0.,  2.,  1.],
>       [ 1.,  0.,  1.],
>       [ 1.,  1.,  1.],
>       [ 1.,  2.,  1.],
>       [ 2.,  0.,  1.],
>       [ 2.,  1.,  1.],
>       [ 2.,  2.,  1.]])
>>>> xx.flags
>  C_CONTIGUOUS : False
>  F_CONTIGUOUS : True
>  OWNDATA : False
>  WRITEABLE : True
>  ALIGNED : True
>  UPDATEIFCOPY : False
>>>> xx.base
> array([[ 0.,  0.,  0.,  1.,  1.,  1.,  2.,  2.,  2.],
>       [ 0.,  1.,  2.,  0.,  1.,  2.,  0.,  1.,  2.],
>       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.]])
>>>> xx == xx.base
> False
>
> When I convert it to a view as a structured array, it produces a
> strange result. I didn't get what I thought I should get
>
>>>> xx.view([('',xx.dtype)]*xx.shape[1])
> array([[(0.0, 0.0, 0.0), (0.0, 1.0, 2.0), (1.0, 1.0, 1.0)],
>       [(1.0, 1.0, 1.0), (0.0, 1.0, 2.0), (1.0, 1.0, 1.0)],
>       [(2.0, 2.0, 2.0), (0.0, 1.0, 2.0), (1.0, 1.0, 1.0)]],
>      dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<f8')])
>
> if I make a copy and then construct a view as structured array, I get
> what I want
>
>>>> xx2 = xx.copy()
>>>> xx2.view([('',xx2.dtype)]*xx2.shape[1])
> array([[(0.0, 0.0, 1.0)],
>       [(0.0, 1.0, 1.0)],
>       [(0.0, 2.0, 1.0)],
>       [(1.0, 0.0, 1.0)],
>       [(1.0, 1.0, 1.0)],
>       [(1.0, 2.0, 1.0)],
>       [(2.0, 0.0, 1.0)],
>       [(2.0, 1.0, 1.0)],
>       [(2.0, 2.0, 1.0)]],
>      dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<f8')])
>
> Are there rules for this behavior or a description in the docs,
> because my mistakes in this are quite difficult to debug? Or do I have
> to make a copy by default as in matlab?

.view() makes a view onto the memory, not onto the
memory-as-if-it-were-normalized-to-C-contiguous-order. Use
ascontiguous() if you need to ensure the latter.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco


More information about the Numpy-discussion mailing list