How to specific multiple dtypes in numpy.ndarray?

John Ladasky john_ladasky at sbcglobal.net
Sat Dec 21 14:16:59 EST 2019


On Thursday, December 19, 2019 at 2:53:18 AM UTC-8, lampahome wrote:
> I meet performance is low when I use struct.unpack to unpack binary data.
> 
> So I tried to use numpy.ndarray
> But meet error when I want to unpack multiple dtypes
> 
> Can anyone teach me~
> 
> Code like below:
> # python3
> import struct
> import numpy as np
> s1 = struct.Struct("@QIQ")
> ss1 = s1.pack(1,11,111)
> np.ndarray((3,), [('Q','I','Q')], ss1)
> # ValueError: mismatch in size of old and new data-descriptor.

Is there some reason that you're calling the np.ndarray constructor directly instead of the np.array convenience function?  The arguments that you pass to each are slightly different.  Generally, you want to use np.array.

The first argument to np.ndarray is the shape.  You appear to want three elements.

The second argument to np.ndarray is the data type (dtype).  It needs to be a SINGLE data type, like 'float' or 'int' or 'object'.  All elements in in array are of the same dtype.  If you want different behavior, I think that you want lists, not arrays.  You can set the dtype to 'object' and you should be able to store any data type as an array element.  But I don't think that offers you any advantages over using ordinary Python lists.

In any case, it appears that you aren't passing a dtype as your second argument.  You're trying to pass the data itself, as a tuple wrapped in a single list.  This seems to be certain to raise an error.

The third argument to np.ndarray is supposed to be the buffer which contains your data.

https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html#numpy.array

ile:///usr/share/doc/python-numpy-doc/html/reference/generated/numpy.array.html#numpy.array


More information about the Python-list mailing list