numpy结构化数组:使用dict指定dtype时无法理解字符串类型 [英] Numpy structured arrays: string type not understood when specifying dtype with a dict
问题描述
如果用不同的方式用相同的字段名称和类型初始化一个结构数组,会发生以下情况:
Here's what happens if I initialize a struct array with the same field names and types in different ways:
>>> a = np.zeros(2, dtype=[('x','int64'),('y','a')])
>>> a
array([(0L, ''), (0L, '')],
dtype=[('x', '<i8'), ('y', 'S')])
因此,使用元组列表进行初始化可以很好地工作.
So initializing with list of tuples works fine.
>>> mdtype = dict(names=['x','y'],formats=['int64','a'])
>>> mdtype
{'names': ['x', 'y'], 'formats': ['int64', 'a']}
>>> a = np.zeros(2,dtype=mdtype)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: data type not understood
因此不使用dict初始化,问题在于字符串类型:
So initializing with a dict doesn't, and the problem is the string type:
>>> mdtype = dict(names=['x','y'],formats=['int64','float64'])
>>> a = np.zeros(2,dtype=mdtype)
>>>
没有问题.有任何想法吗?这是一个顽皮的错误吗?
No problems there. Any ideas? Is this a Numpy bug?
numpy版本:1.8.0
Numpy version: 1.8.0
在Win32上使用Python 2.7.6(默认值,2013年11月10日,19:24:24)[MSC v.1500 64位(AMD64)]
Python 2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bit (AMD64)] on win32
推荐答案
作为一种解决方法,如果您指定字符串宽度,则可以使用:
As a workaround, it works if you specify the string width:
>>> mdtype = dict(names=['x','y'],formats=['int64','a1'])
>>> np.dtype(mdtype)
dtype([('x', '<i8'), ('y', 'S1')])
Probably related to this and this. If it isn't a bug, it is awfully close...
这篇关于numpy结构化数组:使用dict指定dtype时无法理解字符串类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!