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

Python Pandas: เปลี่ยนชื่อคอลัมน์หลายคอลัมน์พร้อมกันด้วย Dictionary

บทนำ

เมธอด rename() ของ DataFrame รองรับการเปลี่ยนชื่อหลายคอลัมน์พร้อมกันโดยส่ง dictionary ไปที่พารามิเตอร์ columns โดย key = ชื่อเก่า, value = ใหม่

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


import pandas as pd

# สร้าง DataFrame
df = pd.DataFrame({
    "Car": ['BMW', 'Mustang', 'Tesla', 'Mustang', 'Mercedes', 'Tesla', 'Audi'],
    "Cubic Capacity": [2000, 1800, 1500, 2500, 2200, 3000, 2000],
    "Reg Price": [7000, 1500, 5000, 8000, 9000, 6000, 1500],
    "Units Sold": [200, 120, 150, 120, 210, 250, 220]
})

print("DataFrame ต้นทาง:")
print(df)

# Dictionary mapping: ชื่อเก่า -> ใหม่
rename_dict = {
    'Car': 'Car Name',
    'Cubic Capacity': 'CC',
    'Reg Price': 'Registration Price',
    'Units Sold': 'Units Purchased'
}

# ใช้ rename() พร้อม inplace=True
df.rename(columns=rename_dict, inplace=True)

print("\nDataFrame หลังเปลี่ยนชื่อ:")
print(df)

ผลลัพธ์


DataFrame ต้นทาง:
       Car  Cubic Capacity  Reg Price  Units Sold
0      BMW            2000       7000         200
1  Mustang            1800       1500         120
2    Tesla            1500       5000         150
3  Mustang            2500       8000         120
4 Mercedes            2200       9000         210
5    Tesla            3000       6000         250
6     Audi            2000       1500         220

DataFrame หลังเปลี่ยนชื่อ:
  Car Name  CC  Registration Price  Units Purchased
0      BMW  2000              7000              200
1  Mustang  1800              1500              120
2    Tesla  1500              5000              150
3  Mustang  2500              8000              120
4 Mercedes  2200              9000              210
5    Tesla  3000              6000              250
6     Audi  2000              1500              220

พารามิเตอร์สำคัญของ rename()

พารามิเตอร์คำอธิบาย
columnsDictionary mapping ชื่อคอลัมน์เก่า → ใหม่
indexDictionary mapping index เก่า → ใหม่
inplaceTrue = แก้ไข DataFrame เดิม, False = คืน DataFrame ใหม่ (default)
errors'raise' (error ถ้า key ไม่มี) หรือ 'ignore' (ข้าม)

เทคนิคเพิ่มเติม

1. ใช้ฟังก์ชันแทน dictionary


# เปลี่ยนชื่อทั้งหมดเป็น lowercase, แทนที่ space ด้วย _
df.rename(columns=lambda x: x.lower().replace(' ', '_'), inplace=True)
# car_name, cc, registration_price, units_purchased

2. เปลี่ยนบางส่วนด้วย str.replace


df.columns = df.columns.str.replace(' ', '_').str.lower()

3. ใช้ set_axis (ต้องระบุลำดับครบ)


df.set_axis(['car_name', 'cc', 'reg_price', 'units_sold'], axis=1, inplace=True)

ข้อควรระวัง

  • inplace=True จะแก้ไข object เดิม ไม่คืนค่า (คืน None)
  • หาก key ใน dictionary ไม่มีใน columns จะ error (ถ้า errors='raise')
  • duplicate column names: rename จะเปลี่ยนทุกคอลัมน์ที่ชื่อตรงกัน

สรุป

df.rename(columns={...}, inplace=True) เป็นวิธีมาตรฐานและอ่านง่ายสำหรับการเปลี่ยนชื่อหลายคอลัมน์ รองรับฟังก์ชัน lambda สำหรับการแปลงชื่อแบบเป็นระบบ