[Numpy-discussion] Numpy structures

Nathaniel Smith njs at pobox.com
Fri Jun 8 15:20:33 EDT 2012

On Fri, Jun 8, 2012 at 11:31 AM, Bob Cowdery <bob at bobcowdery.plus.com> wrote:
> Hi all,
> I am reading a datagram which contains within it a type. The type
> dictates the structure of the datagram. I want to put this into a numpy
> structure, one of which is:
> np.zeros(1,dtype=('2uint8,uint8,uint8,uint32,8uint8,504uint8,8uint8,504uint8'))
> As I don't know what I'm getting until I've read it (it seems I have to
> read the whole datagram in one read) I don't know the shape of the
> structure to use.
> I have tried reading into:
> np.zeros(1032, dtype='uint8')
> and then attempting to copy to the correct structure. How should I do
> this copy as numpy.copy() does not seem to work as if I then try to read
> some fields in the structure it complains the fields don't exist.
> Is there a better way to do this kind of thing, preferably without
> causing a data copy?

I'm not sure I followed what exactly is going on here, but in general
if you want to take a chunk of memory that's inside a numpy array and
re-interpret it in-place as being of a new dtype, then the way you do
that is
  my_array.view(dtype=<new dtype>)


More information about the NumPy-Discussion mailing list