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

Python - Reshape ข้อมูลใน Pandas DataFrame ด้วย Map

ใช้ Series.map() แปลงค่าในคอลัมน์ (เช่น Pass/Fail) ให้เป็นตัวเลข (1/0) เพื่อ Reshape ข้อมูลสำหรับ Machine Learning

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

import pandas as pd

dataFrame = pd.DataFrame({
    "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'],
    "Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass']
})

print("DataFrame ...\n", dataFrame)

# Reshape: Pass -> 1, Fail -> 0
dataFrame['Result'] = dataFrame['Result'].map({'Pass': 1, 'Fail': 0})

print("\nReshaped DataFrame ...\n", dataFrame)

ผลลัพธ์

Reshaped DataFrame ...
   Result Student
0       1    Jack
1       0   Robin
2       0     Ted
3       1 Scarlett
4       1     Kat

คำอธิบาย

  • map(dict) แปลงค่าแต่ละตัวตาม Dictionary Mapping
  • ค่าที่ไม่อยู่ใน Dict จะกลายเป็น NaN
  • เหมาะกับการ Encode Categorical Data (Label Encoding)
  • สำหรับหลายคอลัมน์: ใช้ df.applymap() หรือ df.replace()