Pandas DataFrame round() Method | Round Values to Decimal
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.
Output :
Example 2
Use the round() function to round off all the columns in DataFrame to different decimal places.
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
|
Let’s round off each column to different places
Python3
df. round ({ "A" : 1 , "B" : 2 , "C" : 3 , "D" : 4 })
|
Output :
Last Updated :
01 Feb, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...