[Numpy-discussion] Nice float -> integer conversion?

josef.pktd@gmai... josef.pktd@gmai...
Tue Oct 11 14:18:58 CDT 2011


On Tue, Oct 11, 2011 at 3:06 PM, Derek Homeier
<derek@astro.physik.uni-goettingen.de> wrote:
> On 11 Oct 2011, at 20:06, Matthew Brett wrote:
>
>> Have I missed a fast way of doing nice float to integer conversion?
>>
>> By nice I mean, rounding to the nearest integer, converting NaN to 0,
>> inf, -inf to the max and min of the integer range?  The astype method
>> and cast functions don't do what I need here:
>>
>> In [40]: np.array([1.6, np.nan, np.inf, -np.inf]).astype(np.int16)
>> Out[40]: array([1, 0, 0, 0], dtype=int16)
>>
>> In [41]: np.cast[np.int16](np.array([1.6, np.nan, np.inf, -np.inf]))
>> Out[41]: array([1, 0, 0, 0], dtype=int16)
>>
>> Have I missed something obvious?
>
> np.[a]round comes closer to what you wish (is there consensus
> that NaN should map to 0?), but not quite there, and it's not really
> consistent either!
>
> In [42]: c = np.zeros(4, np.int16)
> In [43]: d = np.zeros(4, np.int32)
> In [44]: np.around([1.6,np.nan,np.inf,-np.inf], out=c)
> Out[44]: array([2, 0, 0, 0], dtype=int16)
>
> In [45]: np.around([1.6,np.nan,np.inf,-np.inf], out=d)
> Out[45]: array([          2, -2147483648, -2147483648, -2147483648], dtype=int32)
>
> Perhaps a starting point to harmonise this behaviour and get it closer to
> your expectations (it still would not be really nice having to define the
> output array first, I guess)...

what numpy is this?

>>> np.array([1.6, np.nan, np.inf, -np.inf]).astype(np.int16)
array([     1, -32768, -32768, -32768], dtype=int16)
>>> np.__version__
'1.5.1'
>>> a = np.ones(4, np.int16)
>>> a[:]=np.array([1.6, np.nan, np.inf, -np.inf])
>>> a
array([     1, -32768, -32768, -32768], dtype=int16)


I thought we get ValueError to avoid nan to zero bugs

>>> a[2] = np.nan
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    a[2] = np.nan
ValueError: cannot convert float NaN to integer

Josef



>
> Cheers,
>                                                        Derek
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>


More information about the NumPy-Discussion mailing list