[英]Why numpy.int16 becomes numpy.float64 after I bit masking?
I am trying to bit masking and discard the LSB of my data[], a numpy.ndarray containing int16. 我正在尝试位屏蔽并丢弃我的data []的LSB,它是一个包含int16的numpy.ndarray。 data = [2,0,4,......,-2,-4] So I create a new array and by bit masking with -2, which should be 1111111111111110 in terms of 16-bit binary.
data = [2,0,4,......,-2,-4]因此,我创建了一个新数组,并使用-2位屏蔽,就16位二进制而言,它应为1111111111111110。
data_new = np.zeros(len(data))
for i in range(len(data)):
data_new[i] = np.int16(data[i] & -2)
Somehow, the output is not array of int16. 不知何故,输出不是int16的数组。 It becomes numpy.float64.
它变为numpy.float64。 And python doesn't allow me to do a bitwise OR to rewrite the LSB.
而且python不允许我按位执行OR来重写LSB。
TypeError: unsupported operand type(s) for |: 'numpy.float64' and 'int'
>>type(data[0])
numpy.int16
>>type(data_new[0])
numpy.float64
The dtype
of the array returned by numpy.zeros
defaults to float64
. 的
dtype
通过返回的数组的numpy.zeros
默认为float64
。 If you want a different type, either explicitly pass the dtype
, eg: 如果要使用其他类型,则可以显式传递
dtype
,例如:
data_new = np.zeros(len(data), np.int16)
or if data
was already the right size and dtype
, use np.zeros_like
to copy its format and structure: 或者,如果
data
已经是正确的大小和dtype
,使用np.zeros_like
复制其格式和结构:
data_new = np.zeros_like(data)
Mind you, in this particular case, the correct solution is likely to just let numpy
do the masking and new array creation in bulk, implicitly, by replacing your creation of the array and loop to populate it with just: 请注意,在这种特定情况下,正确的解决方案可能只是让
numpy
隐式地通过替换数组的创建并循环以仅填充它来进行屏蔽和新数组的创建:
data_new = data & -2
which will run much faster, and "just work" (it will have the same size and dtype
as data
automatically). 它将运行得更快,并且“可以正常工作”(它的大小和
dtype
自动与data
相同)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.