我在numpy array中看到了一个非常奇怪的行为,当我在一个简单的操作中混合了int32和int8数组时,int32数组元素ct[4,0]
在得到+= dleng[4]*4
的结果时似乎变成了8位:
import numpy as np
In[3]: ct = np.zeros((6,1), np.int32)
In[4]: ct
Out[4]:
array([[0],
[0],
[0],
[0],
[0],
[0]], dtype=int32)
In[5]: dleng = np.zeros((6, 1), np.int8)
In[6]: dleng[0] = 2
dleng[1] = 3
dleng[2] = 4
dleng[3] = 7
dleng[4] = 3
dleng[5] = 5
In[7]: dleng
Out[7]:
array([[2],
[3],
[4],
[7],
[3],
[5]], dtype=int8)
In[8]: ct[4] = 117
In[9]: ct
Out[9]:
array([[ 0],
[ 0],
[ 0],
[ 0],
[117],
[ 0]], dtype=int32)
In[10]: ct[4,0] += dleng[4]*4
In[11]: ct
Out[11]:
array([[ 0],
[ 0],
[ 0],
[ 0],
[-127],
[ 0]], dtype=int32)}
有人知道为什么会这样吗?在
dleng[4]*4
是一个数组:而
^{pr2}$ct[4, 0]
是类型为np.int32
的标量:正如@WallyBeaver指出的,
ct[4,0] += dleng[4]*4
就像ct[4,0] = ct[4,0] + dleng[4]*4
。最后一个表达式是一个标量加上一个数组。在这种情况下,数据类型是由数组决定的,因此它最终是np.int8
。在numpy docs中有一条关于此的注释:修复方法是将就地加法写成
因为你在做的是:
实际上是这样:
^{pr2}$产生此功能的:
^{pr3}$然后执行以下操作:
^{pr4}$但实际上是在下面进行这种类型转换:
相关问题 更多 >
编程相关推荐