How to Round Numbers in Pandas

You can use round() and apply() to round up and down numbers in Pandas.

Round to specific decimal places:

df.round(decimals = number of specific decimal places)

Round up numbers:

df[‘DataFrame column’].apply(np.ceil)

Method 3: Round down values:


Data being used

The following is a column of numbers that we are going to use in this tutorial. It uses Numpy to generate an array of random numbers and then convert it into a column in a dataframe.

# import pandas and numpy packages
import pandas as pd
import numpy as np

# create an empty dataframe
df = pd.DataFrame()
# generate a random array of number
array_1 = np.random.rand(5)

# create a column name 'numbers'

# print out the dataframe

The following is the print of the dataframe created by the code above. It is the starting point for all the examples shown later in this tutorial.

0  0.696469
1  0.286139
2  0.226851
3  0.551315
4  0.719469

Example for Specific Decimals

We can specify to have 2 decimals places. The following is the code example.

# set decimals to be 2 and then save it as the same name of the original dataframe
df=df.round(decimals = 2)

# print out the updated version of dataframe

The following is the updated version of dataframe with 2 decimals.

0     0.70
1     0.29
2     0.23
3     0.55
4     0.72

Example for Round Up

You can round up numbers in a dataframe. The following is the Python code showing how to do it.

# code to round up values

# print out the round numbers

The following shows the round numbers. Note that, since all the original numbers are below 1, they all became 1 now.

0      1.0
1      1.0
2      1.0
3      1.0
4      1.0

Example for Round Down

You can also round down. The following is the code.

# code to round down  values

# print out the updated dataframe

The following is the output. We can see all numbers are zero since the original numbers are all smaller than 1.

0      0.0
1      0.0
2      0.0
3      0.0
4      0.0