Convert ndarray from float64 to integer

robintw picture robintw · Jan 13, 2012 · Viewed 141.6k times · Source

I've got an ndarray in python with a dtype of float64. I'd like to convert the array to be an array of integers. How should I do this?

int() won't work, as it says it can't convert it to a scalar. Changing the dtype field itself obviously doesn't work, as the actual bytes haven't changed. I can't seem to find anything on Google or in the documentation - what's the best way to do this?

Answer

kennytm picture kennytm · Jan 13, 2012

Use .astype.

>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1.,  2.,  3.,  4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])

See the documentation for more options.