通常,当dtype与本机类型等效时,它是隐藏的:
>>> import numpy as np
>>> np.arange(5)
array([0, 1, 2, 3, 4])
>>> np.arange(5).dtype
dtype('int32')
>>> np.arange(5) + 3
array([3, 4, 5, 6, 7])但不知何故,这并不适用于楼层划分或模组:
>>> np.arange(5) // 3
array([0, 0, 0, 1, 1], dtype=int32)
>>> np.arange(5) % 3
array([0, 1, 2, 0, 1], dtype=int32)为什么会有区别?
Python3.5.4,NumPy 1.13.1,Windows64bit
发布于 2017-09-18 19:22:57
这里实际上有多个不同的32位整数类型。这可能是个窃听器。
NumPy (偶然?)创建多个不同的带符号32位整数类型,可能对应于C int和long.它们都以numpy.int32的形式显示,但它们实际上是不同的对象。在C级别,我认为类型对象是PyIntArrType_Type和PyLongArrType_Type,生成了这里。
dtype对象具有一个与该dtype标量的类型对象相对应的type属性。type属性是NumPy检查在决定是否在数组的repr中打印dtype信息时使用的
_typelessdata = [int_, float_, complex_]
if issubclass(intc, int):
_typelessdata.append(intc)
if issubclass(longlong, int):
_typelessdata.append(longlong)
...
def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
...
skipdtype = (arr.dtype.type in _typelessdata) and arr.size > 0
if skipdtype:
return "%s(%s)" % (class_name, lst)
else:
...
return "%s(%s,%sdtype=%s)" % (class_name, lst, lf, typename)在numpy.arange(5)和numpy.arange(5) + 3上,.dtype.type是numpy.int_;在numpy.arange(5) // 3或numpy.arange(5) % 3上,.dtype.type是其他32位有符号整数类型.
至于为什么+和//有不同的输出dtype,它们使用不同的类型解析例程。下面是代表//,下面是代表+。//的类型解析寻找一个ufunc内循环,它接受输入可以安全转换到的类型,而+的类型解析对参数应用NumPy类型提升,并选择与结果类型匹配的循环。
发布于 2017-09-18 19:13:16
这可以归结为dtype中的差异,从view中可以看出
In [186]: x = np.arange(10)
In [187]: y = x // 3
In [188]: x
Out[188]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [189]: y
Out[189]: array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3], dtype=int32)
In [190]: x.view(y.dtype)
Out[190]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int32)
In [191]: y.view(x.dtype)
Out[191]: array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3])尽管dtype descr是相同的,但是有一些属性是不同的。但是哪一个呢?
In [192]: x.dtype.descr
Out[192]: [('', '<i4')]
In [193]: y.dtype.descr
Out[193]: [('', '<i4')]
In [204]: x.dtype.type
Out[204]: numpy.int32
In [205]: y.dtype.type
Out[205]: numpy.int32
In [207]: dtx.type is dty.type
Out[207]: False
In [243]: np.core.numeric._typelessdata
Out[243]: [numpy.int32, numpy.float64, numpy.complex128]
In [245]: x.dtype.type in np.core.numeric._typelessdata
Out[245]: True
In [246]: y.dtype.type in np.core.numeric._typelessdata
Out[246]: False因此,从表面上看,y的dtype.type与x的是相同的,但它是一个不同的对象,具有不同的id
In [261]: id(np.int32)
Out[261]: 3045777728
In [262]: id(x.dtype.type)
Out[262]: 3045777728
In [263]: id(y.dtype.type)
Out[263]: 3045777952
In [282]: id(np.intc)
Out[282]: 3045777952将这个额外的type添加到列表中,y就不再显示dtype:
In [267]: np.core.numeric._typelessdata.append(y.dtype.type)
In [269]: y
Out[269]: array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3])所以y.dtype.type是np.intc (和np.intp),x.dtype.type是np.int32 (和np.int_)。
因此,要创建一个显示dtype的数组,请使用np.intc。
In [23]: np.arange(10,dtype=np.int_)
Out[23]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [24]: np.arange(10,dtype=np.intc)
Out[24]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int32)要关闭这个选项,请将np.intc附加到np.core.numeric._typelessdata。
https://stackoverflow.com/questions/46285518
复制相似问题