Examples of how to convert a float array to an integer array in python:
Using the numpy function astype
To convert a float array to an integer array in python, a solution is to use astype, example:
>>> import numpy as np>>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9))>>> Aarray([ 0.4, 1.6, 2.1, -3.7, 2.9])>>> A = A.astype(int)>>> Aarray([ 0, 1, 2, -3, 2])
Round the numbers before converting them in integer
It is also possible to round the numbers and after convert them to integer using the numpy function around
>>> import numpy as np>>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9))>>> Aarray([ 0.4, 1.6, 2.1, -3.7, 2.9])>>> A = np.around(A)>>> Aarray([ 0., 2., 2., -4., 3.])>>> A = A.astype(int)>>> Aarray([ 0, 2, 2, -4, 3])
Note: work also with the function rint, example
>>> import numpy as np>>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9))>>> Aarray([ 0.4, 1.6, 2.1, -3.7, 2.9])>>> A = np.rint(A)>>> Aarray([ 0., 2., 2., -4., 3.])>>> A = A.astype(int)>>> Aarray([ 0, 2, 2, -4, 3])
Truncate the numbers first
>>> import numpy as np>>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9))>>> Aarray([ 0.4, 1.6, 2.1, -3.7, 2.9])>>> A = np.trunc(A)>>> Aarray([ 0., 1., 2., -3., 2.])>>> A = A.astype(int)>>> Aarray([ 0, 1, 2, -3, 2])
Round to the nearest bigger integer
>>> import numpy as np>>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9))>>> Aarray([ 0.4, 1.6, 2.1, -3.7, 2.9])>>> A = np.ceil(A)>>> Aarray([ 1., 2., 3., -3., 3.])>>> A = A.astype(int)>>> Aarray([ 1, 2, 3, -3, 3])
Round to the nearest smaller integer
>>> import numpy as np>>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9))>>> Aarray([ 0.4, 1.6, 2.1, -3.7, 2.9])>>> A = np.floor(A)>>> Aarray([ 0., 1., 2., -4., 2.])>>> A = A.astype(int)>>> Aarray([ 0, 1, 2, -4, 2])
References
| Links | Site |
|---|---|
| astype | docs.scipy.org |
| around | scipy doc |
| rint | doc scipy |
| trunc | doc scipy |
| ceil | doc scipy |
| floor | doc scipy |
| How to convert 2D float numpy array to 2D int numpy array? | stackoverflow |
| Rounding | scipy doc |
| Better rounding in Python's NumPy.around: Rounding NumPy Arrays | stackoverflow |
| are numpy array elements rounded automatically? | stackoverflow |
