[英]numpy fromfile and structured arrays
I'm trying to use numpy.fromfile
to read a structured array (file header) by passing in a user defined data-type . 我正在尝试使用
numpy.fromfile
通过传入用户定义的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? 如何修改
headerfmt
以便将其读取为平面一维数组?
If the count
will always be 1, just do: 如果
count
始终为1,请执行以下操作:
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. 尽管数组的
repr
不会显示字段名称,但是您仍然可以通过字段名称进行索引。
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. 对于您的目的而言,它可能不理想,但无论如何它都很简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.