Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Write a program in Python to round all the elements in a given series
Rounding elements in a Pandas Series is a common data preprocessing task. Python provides multiple approaches: using the built-in round() method, manual iteration, or NumPy functions.
Sample Data
Let's start with a Series containing decimal values ?
import pandas as pd
data = pd.Series([1.3, 2.6, 3.9, 4.8, 5.6])
print("Original Series:")
print(data)
Original Series: 0 1.3 1 2.6 2 3.9 3 4.8 4 5.6 dtype: float64
Using round() Method
The most efficient approach is using Pandas' built-in round() method ?
import pandas as pd
data = pd.Series([1.3, 2.6, 3.9, 4.8, 5.6])
rounded_series = data.round()
print("Rounded Series:")
print(rounded_series)
Rounded Series: 0 1.0 1 3.0 2 4.0 3 5.0 4 6.0 dtype: float64
Using Manual Iteration
You can also iterate through the Series and apply Python's round() function ?
import pandas as pd
data = pd.Series([1.3, 2.6, 3.9, 4.8, 5.6])
rounded_values = []
for index, value in data.items():
rounded_values.append(round(value))
result = pd.Series(rounded_values)
print("Manually Rounded Series:")
print(result)
Manually Rounded Series: 0 1 1 3 2 4 3 5 4 6 dtype: int64
Rounding to Specific Decimal Places
You can specify the number of decimal places using the decimals parameter ?
import pandas as pd
data = pd.Series([1.347, 2.682, 3.926, 4.815, 5.639])
print("Original Series:")
print(data)
print("\nRounded to 1 decimal place:")
print(data.round(1))
print("\nRounded to nearest integer:")
print(data.round(0))
Original Series: 0 1.347 1 2.682 2 3.926 3 4.815 4 5.639 dtype: float64 Rounded to 1 decimal place: 0 1.3 1 2.7 2 3.9 3 4.8 4 5.6 dtype: float64 Rounded to nearest integer: 0 1.0 1 3.0 2 4.0 3 5.0 4 6.0 dtype: float64
Comparison
| Method | Performance | Return Type | Best For |
|---|---|---|---|
series.round() |
Fast (vectorized) | float64 | Standard rounding operations |
| Manual iteration | Slower | int64 | Custom rounding logic |
Conclusion
Use series.round() for efficient rounding operations in Pandas. The method supports decimal places specification and maintains the Series structure. Manual iteration is useful when you need custom rounding logic or integer output.
Advertisements
