ประเภทข้อมูล Category
Pandas มีประเภทข้อมูล category ซึ่งคล้ายกับ factor ใน R
แปลงคอลัมน์ให้เป็นประเภทข้อมูล categorical ได้โดยส่ง 'category' เข้าไปใน method .astype()
เมื่อได้คอลัมน์ที่เป็น categorical แล้ว สามารถดูหมวดหมู่ต่าง ๆ (เรียกว่า levels ใน R) ได้โดยใช้ตัวเข้าถึง .cat แล้วเรียก attribute .categories
อีกกรณีที่นิยมใช้ categorical คือเมื่อต้องการกำหนดลำดับของข้อมูล
เช่น โดยธรรมชาติแล้ว 'low' ควรอยู่ก่อน 'high' ซึ่งใช้ reorder_categories() เพื่อกำหนดลำดับให้กับคอลัมน์ได้
# Reorder categorical levels
df['column_name'].cat.reorder_categories(['low', 'high'], ordered=True)
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python สำหรับผู้ใช้ R
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Convert the type of time column
tips['time'] = ____
# Use the cat accessor to print the categories in the time column
print(____)