How To Round Values In Pandas

Sharing is caring!

Last Updated on July 14, 2022 by Jay

In this tutorial we’ll cover how to round values up, down, to the nearest numbers in pandas.

Let’s use the below simple dataset for the demonstration:

import pandas as pd
import numpy as np

df = pd.DataFrame({'a':[3.14159, 1.234, 3.456, 10.111, -3.3],
                   'b':[12345, 90010, 7600, -9876, 15671.3]})

Pandas round() Syntax

Note this is pandas’ round() method, not the Python built-in round() function. That said, both round() work similarly.

DataFrame.round(decimals=0)

Both DataFrame and Series classes have round() methods that work exactly the same.

Round Values To N Decimals

Simply pass in an integer value into the round() method to round values to the desired decimals. For example, to round to 2 decimals:

df
          a        b
0   3.14159  12345.0
1   1.23400  90010.0
2   3.45600   7600.0
3  10.11100  -9876.0
4  -3.30000  15671.3


df['a'].round(2)
0     3.14
1     1.23
2     3.46
3    10.11
4    -3.30
Name: a, dtype: float64

Round Values Up In Pandas

To round values up, we’ll need to leverage the numpy.ceil() method, which returns the ceiling (i.e. rounded-up number) of the input. The ceil() method can take either one or multiple input values. The below two ways return the same results:

np.ceil(df['a'])
0     4.0
1     2.0
2     4.0
3    11.0
4    -3.0
Name: a, dtype: float64

df['a'].apply(np.ceil)
0     4.0
1     2.0
2     4.0
3    11.0
4    -3.0
Name: a, dtype: float64

In the above code, note the df.apply() takes a function as an input.

Round Values down

Of course, there’s also a numpy.floor() method that returns the floor (i.e. rounded-down number) of the input. The syntax is similar to the above example.

df['a'].apply(np.floor)
0     3.0
1     1.0
2     3.0
3    10.0
4    -4.0
Name: a, dtype: float64

Round Values to Nearest Thousands

The pandas round() method actually allows for negative numbers as input. The negative input specifics the number of positions to the left of the decimal point. For example:

  • round(decimals = -1): round to the nearest tens
  • round(decimals = -2): round to the nearest hundreds
  • and so on

To round to the nearest thousands, we’ll just set decimals = -3.

df['b'].round(-3)
0    12000.0
1    90000.0
2     8000.0
3   -10000.0
4    16000.0
Name: b, dtype: float64

Round A DataFrame With Different Criteria

The decimals argument in the round() method can be either an integer value, or a dictionary. This makes rounding multiple columns easy at the same time.

We can round the first column to 2 decimals, and round the second column to the nearest thousands as the following:

df.round({'a':2, 'b':-3})
       a        b
0   3.14  12000.0
1   1.23  90000.0
2   3.46   8000.0
3  10.11 -10000.0
4  -3.30  16000.0

Additional Resources

Pandas apply() method

Replicate Excel VLOOKUP, HLOOKUP, XLOOKUP in Python

Leave a Reply

Your email address will not be published. Required fields are marked *