[Numpy-discussion] int-ifying a float array

David Goldsmith d.l.goldsmith at gmail.com
Tue Feb 23 00:57:00 EST 2010


Thanks, both, I knew there had to be a better way. :-)

DG

On Mon, Feb 22, 2010 at 7:58 PM, Warren Weckesser <
warren.weckesser at enthought.com> wrote:

> 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
> >
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20100222/6ada6c19/attachment.html>


More information about the NumPy-Discussion mailing list