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

Jingwei Li

Graduate Research assistance at Stony Brook University
linkedin profile url

ProjectPro is an awesome platform that helps me learn much hands-on industrial experience with a step-by-step walkthrough of projects. There are two primary paths to learn: Data Science and Big Data.... Read More

Relevant Projects

NLP Project to Build a Resume Parser in Python using Spacy
Use the popular Spacy NLP python library for OCR and text classification to build a Resume Parser in Python.

BigMart Sales Prediction ML Project in Python
The goal of the BigMart Sales Prediction ML project is to build and evaluate different predictive models and determine the sales of each product at a store.

Build a Autoregressive and Moving Average Time Series Model
In this time series project, you will learn to build Autoregressive and Moving Average Time Series Models to forecast future readings, optimize performance, and harness the power of predictive analytics for sensor data.

Build a Text Generator Model using Amazon SageMaker
In this Deep Learning Project, you will train a Text Generator Model on Amazon Reviews Dataset using LSTM Algorithm in PyTorch and deploy it on Amazon SageMaker.

Build CNN for Image Colorization using Deep Transfer Learning
Image Processing Project -Train a model for colorization to make grayscale images colorful using convolutional autoencoders.

LLM Project to Build and Fine Tune a Large Language Model
In this LLM project for beginners, you will learn to build a knowledge-grounded chatbot using LLM's and learn how to fine tune it.

Deep Learning Project- Real-Time Fruit Detection using YOLOv4
In this deep learning project, you will learn to build an accurate, fast, and reliable real-time fruit detection system using the YOLOv4 object detection model for robotic harvesting platforms.

Build a Review Classification Model using Gated Recurrent Unit
In this Machine Learning project, you will build a classification model in python to classify the reviews of an app on a scale of 1 to 5 using Gated Recurrent Unit.

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.

Loan Eligibility Prediction in Python using H2O.ai
In this loan prediction project you will build predictive models in Python using H2O.ai to predict if an applicant is able to repay the loan or not.