Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python – ปัดทศนิยมค่าคอลัมน์ใน Pandas DataFrame (Display Precision)

ภาพรวม

ปรับจำนวนหลักทศนิยมที่แสดงผลของ DataFrame ใช้ pd.set_option('display.precision', n) – ส่งผลต่อการแสดงผลเท่านั้น ไม่เปลี่ยนข้อมูลจริง

ตัวอย่างโค้ด


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("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.5057
1    Lexus  1500.0000
2    Tesla  5000.9578
3  Mustang  8000.0000
4 Mercedes  9000.7577
5   Jaguar  6000.0000

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

ตัวเลือก Display Options อื่นๆ


pd.set_option('display.float_format', '{:.2f}'.format)  # format คงที่ 2 ตำแหน่ง
pd.set_option('display.max_colwidth', 50)               # ความกว้างคอลัมน์
pd.set_option('display.show_dimensions', True)          # แสดง shape
pd.reset_option('display.precision')                    # รีเซ็ตค่าเริ่มต้น

หากต้องการเปลี่ยนข้อมูลจริง (ไม่ใช่แค่ display)


# ปัดค่าจริงในคอลัมน์
df['Reg_Price'] = df['Reg_Price'].round(2)

# หรือใช้ apply
df = df.round({'Reg_Price': 2, 'Other': 3})

สรุป

วัตถุประสงค์วิธี
แสดงผลสวย (reporting)set_option('display.precision', 2)
เปลี่ยนข้อมูลจริง (calculation)df.round(2) หรือ df['col'].round(2)