Pandas round() | Programiz D11 Phase 2 Skip to main content

Pandas round()

In this tutorial, we will learn about the round() method in Pandas with the help of examples.

The round() method in Pandas is used to round values to a specified number of decimal places.

Example

import pandas as pd

# create a DataFrame
data = {'Value1': [1.1234, 2.3456, 3.5678],
        'Value2': [4.2345, 5.6789, 6.9123]}

df = pd.DataFrame(data)

# round the entire DataFrame to 2 decimal places df_rounded = df.round(2)
print(df_rounded) ''' Output Value1 Value2 0 1.12 4.23 1 2.35 5.68 2 3.57 6.91 '''

round() Syntax

The syntax of the round() method in Pandas is:

df.round(decimals=0, *args, **kwargs)

round() Arguments

The round() method takes following arguments:

  • decimal (optional) - number of decimal places to round to
  • *args and **kwargs (optional) - additional arguments and keyword arguments that can be passed to the function

round() Return Value

The round() method returns a new DataFrame with the data rounded to the given number of decimals.


Example 1: Round DataFrame Elements to Nearest Integer

import pandas as pd

# create a DataFrame
data = {'Value1': [1.1234, 2.3456, 3.5678],
        'Value2': [4.2345, 5.6789, 6.9123]}

df = pd.DataFrame(data)

# round the entire DataFrame elements to nearest integer df_rounded = df.round()
print(df_rounded)

Output


       Value1  Value2
0     1.0     4.0
1     2.0     6.0
2     4.0     7.0

In this example, the round() method rounds the elements of the df Dataframe to the nearest integer.


Example 2: Round Elements to Given Number of Decimal Places

import pandas as pd

# sample data
data = {
    'A': [1.12345, 2.98765],
    'B': [3.10234, 4.76543]
}

# create a DataFrame
df = pd.DataFrame(data)

# round to 3 decimal places
df_rounded = df.round(3)

print(df_rounded)

Output

       A      B
0  1.123  3.102
1  2.988  4.765

In the above example, the round() method is used to round the elements of the df DataFrame.

The argument 3 indicates that we want to round all the numeric values in df to three decimal places.


Example 3: Round Specific Columns

import pandas as pd

# create a DataFrame
data = {'Value1': [1.1234, 2.3456, 3.5678],
        'Value2': [4.2345, 5.6789, 6.9123]}

df = pd.DataFrame(data)

# round specific columns to given number of decimal places df_rounded = df.round({'Value1': 1, 'Value2': 2})
print(df_rounded)

Output

    Value1  Value2
0     1.1    4.23
1     2.3    5.68
2     3.6    6.91

Here, we have passed a dictionary to the round() method where:

  • 'Value1': 1 - specifies that the column labeled Value1 should be rounded to 1 decimal place.
  • 'Value2': 2 - specifies that the column labeled Value2 should be rounded to 2 decimal places.