Contents
Pandas Series.round() Tutorial
In this tutorial, we’ll explore the Series.round() method in Pandas, which is used to round the numeric values in a Pandas Series to the specified number of decimals, with well detailed example programs.
The syntax of Series.round(decimals=0) is:
Series.round(decimals=0)
where
Parameter | Description |
---|---|
decimals | The number of decimals to round to. Default is 0. |
The Series.round() method is useful for formatting and presenting numeric data in a cleaner way.
Examples
1. Round values to the nearest integer using Series.round()
In this example, we’ll use Series.round() to round the numeric values in a Pandas Series to the nearest integer.
We shall pass no arguments to the round() function, and the default value of decimals which is 0 shall take effect.
Python Program
import pandas as pd
# Create a Series with decimal values
original_series = pd.Series([3.14, 2.75, 6.42, 8.91])
# Round values to the nearest integer
rounded_series = original_series.round()
# Print original and rounded Series
print("Original Series:")
print(original_series)
print("\nRounded Series:")
print(rounded_series)
Run Code CopyOutput
Original Series:
0 3.14
1 2.75
2 6.42
3 8.91
dtype: float64
Rounded Series:
0 3.0
1 3.0
2 6.0
3 9.0
dtype: float64
2. Round values to a specific number of decimals using Series.round()
In this example, we’ll use Series.round() to round the numeric values in a Pandas Series to a specific number of decimals (e.g., 2 decimals).
Python Program
import pandas as pd
# Create a Series with decimal values
original_series = pd.Series([3.141592, 2.718281, 1.414214, 0.577216])
# Round values to 2 decimals
rounded_series = original_series.round(decimals=2)
# Print original and rounded Series
print("Original Series:")
print(original_series)
print("\nRounded Series (2 decimals):")
print(rounded_series)
Run Code CopyOutput
Original Series:
0 3.141592
1 2.718281
2 1.414214
3 0.577216
dtype: float64
Rounded Series (2 decimals):
0 3.14
1 2.72
2 1.41
3 0.58
dtype: float64
Summary
In this tutorial, we’ve covered the Series.round() method in Pandas, which is useful for rounding the numeric values in a Series to the desired number of decimals. This method is handy for formatting and presenting data in a more readable way.