0

有没有numpy办法从字符串创建 dtypes?numpy.dtype()几乎是我需要的,但它会产生不一致:

import numpy as np

dtype1 = np.dtype('float32')
dtype2 = np.float32

# This works (prints "same")
if dtype1 == dtype2:
    print("same")

# I want the code in the line below to produce a set with one item
# However, the resulting set is: {dtype('float32'), <class 'numpy.float32'>}
dtypes = {dtype1, dtype2}

# One way to fix the above is to write the following, but this is ugly
dtypes = {np.empty(1, dtype1).dtype, np.empty(1, dtype2).dtype}

有没有一种优雅的方法来解决上述问题?

谢谢

4

1 回答 1

1

虽然您的两个对象在用作dtype参数时做同样的事情,但它们不是同一件事,甚至不是同一类事情:

In [51]: np.dtype('float32')                                                                         
Out[51]: dtype('float32')
In [52]: np.float32                                                                                  
Out[52]: numpy.float32
In [53]: type(np.dtype('float32'))                                                                   
Out[53]: numpy.dtype
In [54]: type(np.float32)                                                                            
Out[54]: type

一个是 的实例np.dtype,另一个是函数。

np.empty(1, 'f').dtype是另一个产生所需 dtype 的字符串,但显然与set.

使用功能:

In [59]: np.float32(1).dtype                                                                         
Out[59]: dtype('float32')
于 2020-07-26T15:48:18.090 回答