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
Python - Round number of places after the decimal for column values in a Pandas DataFrame
To round the number of decimal places displayed for column values in a Pandas DataFrame, you can use the display.precision option. This controls how floating-point numbers are displayed without modifying the underlying data.
Setting Display Precision
First, import the required Pandas library ?
import pandas as pd
Create a DataFrame with decimal values ?
import pandas as pd
dataFrame = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
"Reg_Price": [7000.5057, 1500, 5000.9578, 8000, 9000.75768, 6000]
})
print("Original DataFrame:")
print(dataFrame)
Original DataFrame:
Car Reg_Price
0 BMW 7000.50570
1 Lexus 1500.00000
2 Tesla 5000.95780
3 Mustang 8000.00000
4 Mercedes 9000.75768
5 Jaguar 6000.00000
Using set_option() to Control Precision
Use the set_option() method to set the display precision to 2 decimal places ?
import pandas as pd
dataFrame = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
"Reg_Price": [7000.5057, 1500, 5000.9578, 8000, 9000.75768, 6000]
})
pd.set_option('display.precision', 2)
print("DataFrame with 2 decimal places:")
print(dataFrame)
DataFrame with 2 decimal places:
Car Reg_Price
0 BMW 7000.51
1 Lexus 1500.00
2 Tesla 5000.96
3 Mustang 8000.00
4 Mercedes 9000.76
5 Jaguar 6000.00
Modifying Column Values Permanently
To permanently round the values in a specific column, use the round() method ?
import pandas as pd
dataFrame = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
"Reg_Price": [7000.5057, 1500, 5000.9578, 8000, 9000.75768, 6000]
})
dataFrame['Reg_Price'] = dataFrame['Reg_Price'].round(2)
print("DataFrame with permanently rounded values:")
print(dataFrame)
DataFrame with permanently rounded values:
Car Reg_Price
0 BMW 7000.51
1 Lexus 1500.00
2 Tesla 5000.96
3 Mustang 8000.00
4 Mercedes 9000.76
5 Jaguar 6000.00
Conclusion
Use pd.set_option('display.precision', n) to control decimal display without modifying data. Use round() to permanently round column values to a specified number of decimal places.
Advertisements
