Open In App

Pandas DataFrame round() Method | Round Values to Decimal

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. 

Pandas round() function rounds a DataFrame value to a number with given decimal places. This function provides the flexibility to round different columns by different decimal places.

Example:

Python3




import pandas as pd
import numpy as np
np.random.seed(25)
df = pd.DataFrame(np.random.random([5, 4]), columns =["A", "B", "C", "D"])
df


Syntax

Syntax: DataFrame.round(decimals=0, *args, **kwargs) 

Parameters : 

  • decimals: specifies the number of decimal places to round each column to. If an integer is provided, all columns are rounded to that number. If a dictionary or Series is provided, individual columns can be rounded to different places. Columns not specified in the dictionary or Series remain unchanged.
  • args: (optional) has no effect.
  • kwargs: (optional) has no effect.

Returns: DataFrame object

Examples

Let’s see some examples of how to round DataFrame values to the specified decimal places using the round() method of the NumPy library in Python.

Example 1:

Let’s use the round() function to round off all the decimal values in the DataFrame to 3 decimal places.

Python3




df.round(3)


Output :

Example 2

Use the round() function to round off all the columns in DataFrame to different decimal places.

Python3




# importing pandas as pd
import pandas as pd
  
# importing numpy as np
import numpy as np
  
# setting the seed to re-create the dataframe
np.random.seed(25)
  
# Creating a 5 * 4 dataframe 
df = pd.DataFrame(np.random.random([5, 4]), columns =["A", "B", "C", "D"])
  
# Print the dataframe
df


Let’s round off each column to different places

Python3




# round off the columns in this manner
# "A" to 1 decimal place
# "B" to 2 decimal place
# "C" to 3 decimal place
# "D" to 4 decimal place
  
df.round({"A":1, "B":2, "C":3, "D":4})


Output :



Last Updated : 01 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads