How to convert int32 numpy array into int16 numpy array?

user8026974 picture user8026974 · Apr 2, 2019 · Viewed 11.3k times · Source

I want to conert a numpy array from int32 type to int16 type.

I have an int32 array called array_int32 and I am converting that to int16.

import numpy as np
array_int32 = np.array([31784960, 69074944, 165871616])`
array_int16 = array_int32.astype(np.int16)

After conversion, the array_int16 turns into an array of zeros. I don't know what mistake I am doing. Could anyone help me in this?

Answer

Mark Setchell picture Mark Setchell · Apr 2, 2019

You could discard the bottom 16 bits:

n=(array_int32>>16).astype(np.int16)                          

which will give you this:

array([ 485, 1054, 2531], dtype=int16