4

I'm trying to use numpy.fromfile to read a structured array (file header) by passing in a user defined data-type. For some reason, my structured array elements are coming back as 2-d 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 modify headerfmt so that it will read them as flat 1D arrays?

1 Answer 1

2

If the count will always be 1, just do:

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

You'll still be able to index by field name, though the repr of the array won't show the field names.

For example:

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's simple, at any rate.

Sign up to request clarification or add additional context in comments.

3 Comments

Ahh, I see ... fromfile is giving me an array of count record arrays then? And I'm essentially slicing down a different axis when I do header['f0'].
Yep! Or more precisely, in a structured array, every element is actually a sequence. fromfile with count=1 will always return a length-1 array, and in this case, the first and only element in the array is the sequence you're wanting.
Excellent. If you keep answering all my questions, my boss just might offer you my job ... :-P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.