[Numpy-discussion] int-ifying a float array

David Goldsmith d.l.goldsmith@gmail....
Mon Feb 22 21:56:02 CST 2010


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20100222/179d115f/attachment.html 


More information about the NumPy-Discussion mailing list