Active March 22, 2019 / Viewed 181999 / Comments 0 / Edit
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]] >>> A array[[ 0.4, 1.6, 2.1, -3.7, 2.9]] >>> A = A.astype[int] >>> A array[[ 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
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]] >>> A array[[ 0.4, 1.6, 2.1, -3.7, 2.9]] >>> A = np.rint[A] >>> A array[[ 0., 2., 2., -4., 3.]] >>> A = A.astype[int] >>> A array[[ 0, 2, 2, -4, 3]] >>> import numpy as np >>> A = np.array[[0.4, 1.6, 2.1, -3.7, 2.9]] >>> A array[[ 0.4, 1.6, 2.1, -3.7, 2.9]] >>> A = np.trunc[A] >>> A array[[ 0., 1., 2., -3., 2.]] >>> A = A.astype[int] >>> A array[[ 0, 1, 2, -3, 2]]