[Numpy-discussion] views or copy
josef.pktd at gmail.com
josef.pktd at gmail.com
Mon Apr 6 23:31:03 EDT 2009
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?
Josef
More information about the NumPy-Discussion
mailing list