Pandas Series - round() function
The Pandas Series round() function rounds each value in a Series to the given number of decimal places. The syntax for using this function is mentioned below:
Syntax
Series.round(decimals=0)
Parameters
decimals |
Optional. Specify int to indicate number of decimal places to round to. If decimals is negative, it specifies the number of positions to the left of the decimal point. |
Return Value
Returns rounded values of the Series.
Example: Rounding a Series
In the example below, the round() function is used to round a Series to a specified number of decimal places.
import pandas as pd import numpy as np x = pd.Series([5.344, 3.925, 2.150, 4.229]) print("The Series contains:") print(x) #rounding to 0 decimal places print("\nx.round() returns:") print(x.round()) #rounding to 1 decimal places print("\nx.round(2) returns:") print(x.round(2))
The output of the above code will be:
The Series contains: 0 5.344 1 3.925 2 2.150 3 4.229 dtype: float64 x.round() returns: 0 5.0 1 4.0 2 2.0 3 4.0 dtype: float64 x.round(2) returns: 0 5.34 1 3.92 2 2.15 3 4.23 dtype: float64
Example: Rounding selected series in a DataFrame
Similarly, the round() function can be applied on selected series/column of a given DataFrame. Consider the following example.
import pandas as pd import numpy as np df = pd.DataFrame({ "Bonus": [5.344, 3.925, 2.150, 4.229], "Salary": [60.227, 62.550, 65.725, 59.328], "Other perks":[2.227, 1.750, 2.527, 2.958]}, index= ["John", "Marry", "Sam", "Jo"] ) print("The DataFrame is:") print(df, "\n") #rounding 'Salary' series print("\ndf['Salary'].round(2) returns:") print(df["Salary"].round(2))
The output of the above code will be:
The DataFrame is: Bonus Salary Other perks John 5.344 60.227 2.227 Marry 3.925 62.550 1.750 Sam 2.150 65.725 2.527 Jo 4.229 59.328 2.958 df['Salary'].round(2) returns: John 60.23 Marry 62.55 Sam 65.72 Jo 59.33 Name: Salary, dtype: float64
❮ Pandas Series - Functions