numpy question (fairly basic, I think)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Dec 13 18:52:43 EST 2014


Albert-Jan Roskam wrote:

> Hi,
> 
> I am new to numpy. I am reading binary data one record at a time (I have
> to) and I would like to store all the records in a numpy array which I
> pre-allocate. Below I try to fill the empty array with exactly one record,
> but it is filled with as many rows as there are columns. Why is this? It
> is probably something simple, but I am stuck! It is like the original
> record is not unpacked *as in tuple unpacking) into the array, so it
> remains one chunk, not an (nrows, ncols) structure.

Can you simplify the example to something shorter that focuses on the issue
at hand? It isn't clear to me which bits of the code you show are behaving
the way you expect and which bits are not.


To get you started, here is what I got working:


import numpy as np

# one binary record
s = '\x00\x01\x00\xff'*2  # eight bytes makes one C double
# read it into a structured array
formats = ['<d']
names = ["v%02d" % i for i in range(len(formats))]
dt = np.dtype({'formats': formats, "names": names})
record = np.fromstring(s, dtype=dt)


which gives this for record:

array([(-5.4874686660912e+303,)],
      dtype=[('v00', '<f8')])


Is that what you expected? If not, what did you expect?

Now modify the example the *least amount possible* to demonstrate the issue.



-- 
Steven




More information about the Python-list mailing list