Pandas: Rounding when converting float to integer

Learn, how to round when converting float to integer in Python Pandas? By Pranit Sharma Last updated : October 06, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose we are given the Pandas dataframe and one of its columns contains float values, we need to convert the float values into integers and also, we need the round-off result of these values simultaneously.

Rounding when converting float to integer

However, we have floor() and ceil() methods that can do the same but instead of using the floor() and ceil() methods, we just need a simple approach to round off the values automatically.

Hence, we will use the data frame round() method along with the astype() method for converting the float value to an integer value and getting the round-off result of these values.

Let us assume that we have a value of 1.6 the round method will convert this value into 2 whereas the same round method will convert 1.3 into 1.

Let us understand with the help of an example,

Python program to round when converting float to integer

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {'a':[4.5,6.7,6.4,2.4,7.5]}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original df
print("Original DataFrame:\n",df,"\n")

# Getting round off values
res = df.round(0).astype(int)

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Example: Pandas: Rounding when converting float to integer

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.