robintw
robintw

Reputation: 28591

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?

Upvotes: 74

Views: 227219

Answers (5)

John Henckel
John Henckel

Reputation: 11417

If you are looking to use less memory, the following code will return the smallest integer type (less than 64).

def reduced_type(arr:np.ndarray) -> np.ndarray:
    if arr.min() < 0: return arr
    num_bits = int(math.log2(arr.max() or 1) + 1)
    if num_bits <= 8: return arr.astype(np.uint8)
    if num_bits <= 16: return arr.astype(np.uint16)
    if num_bits <= 32: return arr.astype(np.uint32)
    return arr

obviously, you can tweak this to suit your application.

Upvotes: 0

Ronan Hansel
Ronan Hansel

Reputation: 138

All I used is

numpyfloat = (1.0, 2.0, 4.0)
a = numpy.array(numpyfloat, dtype=numpy.int)

That's just it

Upvotes: 4

MSeifert
MSeifert

Reputation: 152810

While astype is probably the "best" option there are several other ways to convert it to an integer array. I'm using this arr in the following examples:

>>> import numpy as np
>>> arr = np.array([1,2,3,4], dtype=float)
>>> arr
array([ 1.,  2.,  3.,  4.])

The int* functions from NumPy

>>> np.int64(arr)
array([1, 2, 3, 4])

>>> np.int_(arr)
array([1, 2, 3, 4])

The NumPy *array functions themselves:

>>> np.array(arr, dtype=int)
array([1, 2, 3, 4])

>>> np.asarray(arr, dtype=int)
array([1, 2, 3, 4])

>>> np.asanyarray(arr, dtype=int)
array([1, 2, 3, 4])

The astype method (that was already mentioned but for completeness sake):

>>> arr.astype(int)
array([1, 2, 3, 4])

Note that passing int as dtype to astype or array will default to a default integer type that depends on your platform. For example on Windows it will be int32, on 64bit Linux with 64bit Python it's int64. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy types like np.int32 or np.int64.

Upvotes: 14

benjaminmgross
benjaminmgross

Reputation: 2102

There's also a really useful discussion about converting the array in place, In-place type conversion of a NumPy array. If you're concerned about copying your array (which is whatastype() does) definitely check out the link.

Upvotes: 6

kennytm
kennytm

Reputation: 523724

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.

Upvotes: 95

Related Questions