[Numpy-discussion] int-ifying a float array

Warren Weckesser warren.weckesser at enthought.com
Mon Feb 22 22:58:57 EST 2010


Here's another way, using 'astype':

In [1]: import numpy as np

In [2]: x = np.array([1.0, 2.0, 3.0])

In [3]: y = x.astype(int)

In [4]: y
Out[4]: array([1, 2, 3])



Warren

David Goldsmith wrote:
> Hi!  Is there a less cumbersome way (e.g., one that has a "cast-like" 
> syntax and/or leverages broadcasting) than what follows to convert an 
> array of floats to an array of ints?  Here's what works:
>
> >>> import numpy as N
> >>> t = N.array([0.0, 1.0]); t.dtype
> dtype('float64')
> >>> t = N.array(t, dtype=int); t; t.dtype
> array([0, 1])
> dtype('int32')
>
> Here's three ways that don't:
>
> >>> t = N.array([0.0, 1.0])
> >>> int(t)
> Traceback (most recent call last):
>   File "<input>", line 1, in <module>
> TypeError: only length-1 arrays can be converted to Python scalars
> >>> N.int(t)
> Traceback (most recent call last):
>   File "<input>", line 1, in <module>
> TypeError: only length-1 arrays can be converted to Python scalars
> >>> t.dtype = N.int
> >>> t
> array([         0,          0,          0, 1072693248])
>
> It doesn't really surprise me that none of these cast-like (or 
> attribute change in the last case) ways work (though it might be nice 
> if at least one of them did), but perhaps I'm just not guessing the 
> syntax right...
>
> Thanks,
>
> DG
> ------------------------------------------------------------------------
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>   




More information about the NumPy-Discussion mailing list