Numpy fromfile and structured arrays

I am trying to use numpy.fromfile to read a structured array (file header), passing in a custom data type . For some reason, my structured array elements are returned as 2-dimensional arrays instead of flat 1D arrays:

 headerfmt='20i,20f,a80' dt = np.dtype(headerfmt) header = np.fromfile(fobj,dtype=dt,count=1) ints,floats,chars = header['f0'][0], header['f1'][0], header['f2'][0] # ^? ^? ^? 

How do I change headerfmt to read them as 1D flat arrays?

+4
source share
1 answer

If count will always be 1, just do:

 header = np.fromfile(fobj, dtype=dt, count=1)[0] 

You can still index by field name, although the array repr will not display field names.

For instance:

 import numpy as np headerfmt='20i,20f,a80' dt = np.dtype(headerfmt) # Note the 0-index! x = np.zeros(1, dtype=dt)[0] print x['f0'], x['f1'], x['f2'] ints, floats, chars = x 

It may or may not be ideal for your purposes, but it is simple, anyway.

+2
source

Source: https://habr.com/ru/post/1485046/


All Articles