Python Practice › NumPy Programs › Program 73
Float array to integers
Write a NumPy program to convert an array of floats to integers.
Input
[[6.7, 5.2], [9.4, 2.7]]
Output
[[6 5] [9 2]] [[7 5] [9 3]]
Approach
astype(int)truncates; round first if needed.
Solution
import numpy as npa = np.array([[6.7, 5.2], [9.4, 2.7]])print(a.astype(int))print(np.rint(a).astype(int))Output
[[6 5] [9 2]] [[7 5] [9 3]]
Line by line
Line 3
Truncation drops the decimals.
Line 4
rint rounds to the nearest integer first.
Learn the concept
New to this topic? Read the lesson, then come back.