I'm trying to get a view of 2D ndarray as a record or structured array without copying. This seems to work fine if a
owns it data
>>> a = np.array([[ 1, 391, 14, 26],
[ 17, 371, 15, 30],
[641, 340, 4, 7]])
>>> b = a.view(zip('abcd',[a.dtype]*4))
array([[(1, 391, 14, 26)],
[(17, 371, 15, 30)],
[(641, 340, 4, 7)]],
dtype=[('a', '<i8'), ('b', '<i8'), ('c', '<i8'), ('d', '<i8')])
>>> b.base is a
True
But if a
is already a view, this fails. Here's an example
>>> b = a[:,[0,2,1,3]]
>>> b.base is None
False
>>> b.view(zip('abcd',[a.dtype]*4))
ValueError: new type not compatible with array.
Interestingly, in this case b.base
is a transpose of the view
>>> (b.base == b.T).all()
True
So it makes sense that numpy couldn't create the view of that that I wanted.
However, if I use
>>> b = np.take(a,[0,2,1,3],axis=1)
This results in b
being a proper copy of the data so that taking the recarray view works. Side question: Can someone explain this behavior in constrast to fancy indexing?
My question is, am I going about this the wrong way? Is taking a view the way I'm doing it not supported? If so, what would be the proper way to do it?