การเข้ารหัสตัวแปรหมวดหมู่
ในชุดข้อมูล UFO มีบางคอลัมน์ที่ต้องเข้ารหัสก่อนนำไปใช้กับ scikit-learn ได้ แบบฝึกหัดนี้จะฝึกการแปลงข้อมูลโดยใช้ทั้งวิธี binary encoding และ one-hot encoding
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การเตรียมข้อมูลสำหรับ Machine Learning ด้วย Python
คำแนะนำการฝึกหัด
- ใช้
apply()เขียนlambdaแบบมีเงื่อนไขที่คืนค่า1เมื่อค่าเป็น"us"และคืนค่า0ในกรณีอื่น - แสดงจำนวนค่า
.unique()ในคอลัมน์type - ใช้
pd.get_dummies()สร้างชุดข้อมูลแบบ one-hot encoded จากคอลัมน์type - สุดท้าย ใช้
pd.concat()เพื่อรวมตัวแปรที่เข้ารหัสแล้วในtype_setเข้ากับชุดข้อมูลufo
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Use pandas to encode us values as 1 and others as 0
ufo["country_enc"] = ufo["country"].____
# Print the number of unique type values
print(len(____.unique()))
# Create a one-hot encoded set of the type values
type_set = ____
# Concatenate this set back to the ufo DataFrame
ufo = pd.concat([____, ____], axis=1)