如何从字符串"long"创建一个 numpy dtype?



我有一个包含字符串'long'的变量。如何从这个字符串中创建一个类型等于long的numpy dtype对象?我有一个文件,里面有很多数字和相应的类型。intfloat等都没有问题,只有long不起作用。我不想在我的代码中硬编码一些替换long -> int32左右。

>>> np.dtype('long')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: data type not understood

还有:有没有一种方法可以在纯python中从字符串创建变量类型?我的意思是,我想要int.__name__的反转,它将类型名称转换为字符串。

在这种特殊情况下,我认为您可以使用getattrnumpy模块本身获得它:

>>> import numpy as np
>>> np.dtype('long')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: data type not understood

但是:

>>> getattr(np, 'long')
<type 'long'>
>>> np.dtype(getattr(np, 'long'))
dtype('int64')
>>> np.dtype(getattr(np, 'int'))
dtype('int32')
>>> np.dtype(getattr(np, 'float64'))
dtype('float64')
>>> np.dtype(getattr(np, 'float'))
dtype('float64')

最新更新