Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How to convert real numpy array to int numpy array? Tried using map directly to array but it did not work.

share|improve this question

2 Answers 2

up vote 105 down vote accepted

Use the astype method.

>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> x.astype(int)
array([[1, 2],
       [1, 2]])
share|improve this answer
3  
Just make sure you don't have np.infor np.nan in your array, since they have surprising results. For example, np.array([np.inf]).astype(int) outputs array([-9223372036854775808]). –  Garrett Jan 22 at 8:42

Some numpy functions for how to control the rounding: rint, floor,trunc, ceil. depending how u wish to round the floats, up, down, or to the nearest int.

>>> x = np.array([[1.0,2.3],[1.3,2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> y = np.trunc(x)
>>> y
array([[ 1.,  2.],
       [ 1.,  2.]])
>>> z = np.ceil(x)
>>> z
array([[ 1.,  3.],
       [ 2.,  3.]])
>>> t = np.floor(x)
>>> t
array([[ 1.,  2.],
       [ 1.,  2.]])
>>> a = np.rint(x)
>>> a
array([[ 1.,  2.],
       [ 1.,  3.]])

To make one of this in to int, or one of the other types in numpy, astype (as answered by BrenBern):

a.astype(int)
array([[1, 2],
       [1, 3]])

>>> y.astype(int)
array([[1, 2],
       [1, 2]])
share|improve this answer
1  
Exactly what I was looking for. astype is often too generic, and I think it probably is more useful when doing intx - inty conversions. When I want to do float - int conversion being able to choose the kind of rounding is a nice feature. –  Bakuriu Sep 11 '12 at 7:03
4  
So the simplest way to safely convert almost-ints like 7.99999 to ints like 8, is np.rint(arr).astype(int)? –  endolith Oct 12 '12 at 18:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.