I have a variable that contains the string 'long'. How can I create a numpy dtype object with some type equivalent to long from this string? I have a file with many numbers and the corresponding types. int
, float
etc. are no problems, only long
doesn't work. I don't want to hardcode some replacement long -> int32
or so in my code.
>>> np.dtype('long')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: data type not understood
Also: Is there a way to create a variable type from a string in pure python? I mean, I want the inverse of int.__name__
, which converts the type name into a string.
In this particular case, I think you can use getattr
to get it from the numpy
module itself:
>>> import numpy as np
>>> np.dtype('long')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: data type not understood
but:
>>> 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')
np.dtype(eval('long'))
如果你准备好在你的代码中加入eval
,你会做什么。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.