Python - Round number of places after the decimal for column values in a Pandas DataFrame

pythonserver side programmingprogramming更新于 2025/11/1 14:04:17

To round number of places after the decimal, use the display.precision attribute of the Pandas.

首先,导入所需的 Pandas 库 −

import pandas as pd

创建一个包含 2 列的 DataFrame −

dataFrame = pd.DataFrame(
       {
    "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
    "Reg_Price": [7000.5057, 1500, 5000.9578, 8000, 9000.75768, 6000]
    
    }
)

使用 set_option() 方法设置精度。我们已将精度值设置为 2 −

pd.set_option('display.precision', 2)

示例

以下是完整代码 −

import pandas as pd

# 创建 DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
      "Reg_Price": [7000.5057, 1500, 5000.9578, 8000, 9000.75768, 6000]

   }
)

print"DataFrame ...\n",dataFrame

pd.set_option('display.precision', 2)
print"\nUpdated dataframe with rounding decimal values...\n", dataFrame

输出

这将产生以下输出 −

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

Updated dataframe with rounding decimal 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

相关文章


有用资源