简体   繁体   中英

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 = [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_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. It becomes numpy.float64. And python doesn't allow me to do a bitwise OR to rewrite the 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 . If you want a different type, either explicitly pass the dtype , eg:

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_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:

data_new = data & -2

which will run much faster, and "just work" (it will have the same size and dtype as data automatically).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM