正如标题中所述,我愿意知道np.dtype和np.dtype.name之间的区别。当我使用它们时,我发现它们提供了如下所示的输出:
dt = np.array([[(1, 5, 2), (2, 4.0, 7)], [(6, 4, 2), (2, 8, 10)]])
print('\nData type of array elements:', dt.dtype)
print('\nName of data type:', dt.dtype.name)输出是
数组元素的
数据类型: float64
数据类型名称: float64
发布于 2021-10-06 18:28:01
In [62]: arr = np.array([[(1, 5, 2), (2, 4.0, 7)], [(6, 4, 2), (2, 8, 10)]])
In [63]: arr
Out[63]:
array([[[ 1., 5., 2.],
[ 2., 4., 7.]],
[[ 6., 4., 2.],
[ 2., 8., 10.]]])对于这个简单的dtype,name与str/print表示相同。
In [64]: arr.dtype
Out[64]: dtype('float64') # the repr print
In [65]: arr.dtype.name
Out[65]: 'float64'
In [66]: print(arr.dtype)
float64但是,在名称和显示不同的情况下,可以构造更复杂的dtype。例如,由于构造函数具有内部元组,所以我可以创建一个具有复合dtype的数组,即structured数组:
In [69]: arr = np.array([[(1, 5, 2), (2, 4.0, 7)], [(6, 4, 2), (2, 8, 10)]], dtype='i,f,f8')
In [70]: arr
Out[70]:
array([[(1, 5., 2.), (2, 4., 7.)],
[(6, 4., 2.), (2, 8., 10.)]],
dtype=[('f0', '<i4'), ('f1', '<f4'), ('f2', '<f8')])
In [71]: arr.dtype
Out[71]: dtype([('f0', '<i4'), ('f1', '<f4'), ('f2', '<f8')])
In [72]: arr.dtype.name
Out[72]: 'void128'
In [73]: arr.dtype.fields
Out[73]:
mappingproxy({'f0': (dtype('int32'), 0),
'f1': (dtype('float32'), 4),
'f2': (dtype('float64'), 8)})发布于 2021-10-06 12:02:20
如果打印一个对象,它会问对象要打印什么,即它调用它为"repr“方法。Python对象总是这样的,但是您可以自己定义它们。例如。
class foo:
def __init__(self):
pass
print(foo())给我<__main__.foo object at 0x10b737280>
而
class foo:
def __init__(self):
pass
def __repr__(self):
return "__repr__"
print(foo())给我__repr__。
因此,numpy类型的对象float64有两个方法给出名称。一个是手动调用,另一个是python在请求对象的字符串表示时隐式调用,例如,如果您打印对象。
你可以这样看得更清楚
dt = np.array([[(1, 5, 2), (2, 4.0, 7)], [(6, 4, 2), (2, 8, 10)]])
print('Type of data type of array elements:', type(dt.dtype))
print('Type of name of data type:', type(dt.dtype.name)).它给了你
Type of data type of array elements: <class 'numpy.dtype[float64]'>
Type of name of data type: <class 'str'>https://stackoverflow.com/questions/69464797
复制相似问题