python – numpy fromfile和结构化数组

我试图通过传入
user defined data-type来使用
numpy.fromfile来读取
structured array(文件头).出于某种原因,我的结构化数组元素将以2-d数组而不是平坦的1D数组返回:

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]
#                                ^?               ^?               ^?

如何修改headerfmt以便将它们作为平面1D数组读取?

最佳答案 如果计数总是1,那么只需:

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

您仍然可以按字段名称编制索引,但数组的repr不会显示字段名称.

例如:

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

对于您的目的,它可能是也可能不是理想的,但无论如何它都很简单.

点赞