Search code examples
pythonnumpyscipy

Convert ndarray from float64 to integer


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?


Solution

  • 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.