Python Practice › NumPy Programs › Program 73

Float array to integers

EasyNumPy Programs · 73 of 100

Write a NumPy program to convert an array of floats to integers.

Advertisement
Input
[[6.7, 5.2], [9.4, 2.7]]
Output
[[6 5]
 [9 2]]
[[7 5]
 [9 3]]

Approach

  1. astype(int) truncates; round first if needed.

Solution

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

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More numpy programs

← All 100 NumPy Programs