How to round a NumPy array to nearest integer in Python?

This recipe explains how to round a numpy array to nearest integer in Python.

Rounding numbers may seem straightforward, but in the world of data analysis and scientific computing, it takes on a whole new level of significance. Data professionals and researchers often deal with practical datasets filled with real-world measurements, observations, and calculations. Precision is key, and knowing how to round numbers correctly can make a substantial difference in the accuracy of our results. 

How to round a NumPy array to nearest integer in Python?

In this exploration, we'll dive into the essential skill of rounding in Python, specifically focusing on how to round a NumPy array to the nearest integer. So, this guide is a short example of how to round a NumPy array. Let's get started.

Learn how to build Regression (Linear,Ridge,Lasso) Models in NumPy Python 

NumPy Array Round up Examples

In the data science domain, rounding serves as a useful tool for simplifying data, enhancing readability, and facilitating interpretation. NumPy, a versatile Python library, offers an array of functions for rounding array elements, encompassing numpy.around(), numpy.floor(), numpy.ceil(), and numpy.trunc(). Here are some examples of rounding up NumPy arrays using various rounding functions:

 1) Using numpy.ceil()

import numpy as np

# Create a NumPy array

arr = np.array([1.2, 2.7, 3.1, 4.8])

# Round up the elements using numpy.ceil()

rounded_up = np.ceil(arr)

print(rounded_up)

Output:

[2. 3. 4. 5.]

In this example, numpy.ceil() is used to round up the elements of the array to the nearest integer greater than or equal to each element.

2. Using numpy.round()

import numpy as np

# Create a NumPy array

arr = np.array([1.2, 2.7, 3.1, 4.8])

# Round up the elements using numpy.round()

rounded_up = np.round(arr)

print(rounded_up)

Output:

[1. 3. 3. 5.]

numpy.round() is used here to round the elements to the nearest integer. It follows the standard rounding rules.

3. Using numpy.ceil() with Negative Numbers

import numpy as np

# Create a NumPy array with negative numbers

arr = np.array([-1.2, -2.7, -3.1, -4.8])

# Round up the negative elements using numpy.ceil()

rounded_up = np.ceil(arr)

print(rounded_up)

Output:

[-1. -2. -3. -4.]

Even with negative numbers, numpy.ceil() rounds up to the nearest integer greater than or equal to each element.

These examples showcase how NumPy's rounding functions can be used to round up elements in a NumPy array to the desired precision. Let us now look at two interesting examples that aim to round every value in numpy array.

How to round NumPy array to 2 decimal places?

Here's a short guide on how to round a NumPy array to two decimal places in Python:

Step 1: Import NumPy Library

Use the code below to import NumPy in your Python script or Jupyter Notebook:

import numpy as np

Step 2: Create Your NumPy Array

Next, create the NumPy array that you want to round to two decimal places. Here's an example array:

original_array = np.array([3.14159265, 2.71828183, 1.41421356, 0.57721566])

Step 3: Use numpy.round()

To round the elements in your NumPy array to two decimal places, you can use the numpy.round() function. Pass your original array and the number of decimal places you want as arguments. In this case, we want two decimal places, so we pass 2 as the second argument:

rounded_array = np.round(original_array, 2)

Step 4: Display the Rounded Array

Now, you can print or display the rounded array to see the result:

print(rounded_array)

Step-5 Look at the Output

[3.14 2.72 1.41 0.58]

The NumPy array has now been rounded to two decimal places. This is a handy technique for controlling the precision of one’s data when working with numerical arrays in Python.

How to round away from zero a float array using numpy?

We will step by step take a look an example of.numpy round all elements in array

Step 1 - Import the NumPy library

import numpy as np

Let's pause and look at these imports. Numpy is generally used for working with arrays and performing mathematical operations in domain of linear algebra, fourier transform and matrices

Step 2 - Defining round_array function

def round_array(x,y):

    return np.round(x,y)

This function takes x and y as input and return x rounded to y decimal places.

Step 3 - Setup the Data

test = np.array([32.11, 51.5, 0.112])

We have simply setup one random array

Step 4 - Printing rounded off array

print(round_array(test,0))

Firslty, we call our round_array function sending in our test dataset and 0 (places to which it will be rounded.

Step 5 - Let’s look at our dataset now

Once we run the above code snippet, we will see:

[32. 52.  0.]

Master NumPy with ProjectPro!

NumPy's utility extends far beyond rounding in data science projects. Its comprehensive capabilities encompass data manipulation, array operations, statistical analysis, and more. To deepen your expertise, consider exploring the diverse functions NumPy offers. For hands-on experience and practical application, cehck out ProjectPro, a platform that provides a wealth of solved projects in data science and big data—ideal for honing your skills and advancing in this dynamic field.

 

What Users are saying..

profile image

Savvy Sahai

Data Science Intern, Capgemini
linkedin profile url

As a student looking to break into the field of data engineering and data science, one can get really confused as to which path to take. Very few ways to do it are Google, YouTube, etc. I was one of... Read More

Relevant Projects

MLOps using Azure Devops to Deploy a Classification Model
In this MLOps Azure project, you will learn how to deploy a classification machine learning model to predict the customer's license status on Azure through scalable CI/CD ML pipelines.

Azure Deep Learning-Deploy RNN CNN models for TimeSeries
In this Azure MLOps Project, you will learn to perform docker-based deployment of RNN and CNN Models for Time Series Forecasting on Azure Cloud.

PyCaret Project to Build and Deploy an ML App using Streamlit
In this PyCaret Project, you will build a customer segmentation model with PyCaret and deploy the machine learning application using Streamlit.

Build a Similar Images Finder with Python, Keras, and Tensorflow
Build your own image similarity application using Python to search and find images of products that are similar to any given product. You will implement the K-Nearest Neighbor algorithm to find products with maximum similarity.

AWS MLOps Project to Deploy a Classification Model [Banking]
In this AWS MLOps project, you will learn how to deploy a classification model using Flask on AWS.

Deep Learning Project for Text Detection in Images using Python
CV2 Text Detection Code for Images using Python -Build a CRNN deep learning model to predict the single-line text in a given image.

Credit Card Fraud Detection as a Classification Problem
In this data science project, we will predict the credit card fraud in the transactional dataset using some of the predictive models.

Multilabel Classification Project for Predicting Shipment Modes
Multilabel Classification Project to build a machine learning model that predicts the appropriate mode of transport for each shipment, using a transport dataset with 2000 unique products. The project explores and compares four different approaches to multilabel classification, including naive independent models, classifier chains, natively multilabel models, and multilabel to multiclass approaches.

Build CNN Image Classification Models for Real Time Prediction
Image Classification Project to build a CNN model in Python that can classify images into social security cards, driving licenses, and other key identity information.

NLP Project on LDA Topic Modelling Python using RACE Dataset
Use the RACE dataset to extract a dominant topic from each document and perform LDA topic modeling in python.