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

Matthew Brett matthew.brett@gmail....
Tue Oct 11 14:32:13 CDT 2011


Hi,

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)...

Thanks - it hadn't occurred to me to try around with an output array -
an interesting idea.

But - isn't this different but just as bad?

Best,

Matthew


More information about the NumPy-Discussion mailing list