我有一个包含字符串“long”的变量。如何从这个字符串创建一个 numpy dtype 对象,其类型等同于 long?我有一个包含许多数字和相应类型的文件。 int
、float
等都没有问题,只有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__
的逆函数,它将类型名称转换为字符串。
最佳答案
在这种特殊情况下,我认为您可以使用 getattr
从 numpy
模块本身获取它:
>>> 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')
关于python - 如何从字符串 'long' 创建一个 numpy dtype?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12217385/