使用numpy的flatten_dtype与带标题的结构化dtype
我通常不在这些论坛上发问,但我到处搜索过,还是没找到关于这个问题的任何信息。
我正在使用结构化数组来存储实验数据。我用标题来存储关于我的字段的信息,这里指的是计量单位。当我对我的数据类型(dtype)调用 numpy.lib.io.flatten_dtype() 时,我得到了:
ValueError: too many values to unpack
File "c:\Python25\Lib\site-packages\numpy\lib\_iotools.py", line 78, in flatten_dtype
(typ, _) = ndtype.fields[field]
其实我本来不太在意这个,除了因为 numpy.genfromtxt() 也会调用 numpy.lib.io.flatten_dtype(),而我需要从文本文件中导入我的数据。
我在想我是不是做错了什么。flatten_dtype() 是不是不支持标题?有没有什么方法可以解决 genfromtxt() 的问题?
这是我代码的一部分:
import numpy
fname = "C:\\Somefile.txt"
dtype = numpy.dtype([(("Amps","Current"),"f8"),(("Volts","Voltage"),"f8")])
myarray = numpy.genfromtxt(fname,dtype)
1 个回答
1
这里有一个可能的解决办法:
因为你自定义的 dtype
造成了问题,所以可以使用一个扁平化的 dtype
来代替:
In [77]: arr=np.genfromtxt('a',dtype='f8,f8')
In [78]: arr
Out[78]:
array([(1.0, 2.0), (3.0, 4.0)],
dtype=[('f0', '<f8'), ('f1', '<f8')])
然后使用 astype
来转换成你想要的 dtype
:
In [79]: arr=np.genfromtxt('a',dtype='f8,f8').astype(dtype)
In [80]: arr
Out[80]:
array([(1.0, 2.0), (3.0, 4.0)],
dtype=[(('Amps', 'Current'), '<f8'), (('Volts', 'Voltage'), '<f8')])
编辑:另一个选择是对 numpy.lib.io.flatten_dtype
进行修改:
import numpy
import numpy.lib.io
def flatten_dtype(ndtype):
"""
Unpack a structured data-type.
"""
names = ndtype.names
if names is None:
return [ndtype]
else:
types = []
for field in names:
typ_fields = ndtype.fields[field]
flat_dt = flatten_dtype(typ_fields[0])
types.extend(flat_dt)
return types
numpy.lib.io.flatten_dtype=flatten_dtype