การตั้งค่าและลบ index
pandas ช่วยให้กำหนดคอลัมน์ให้เป็น index ได้ ซึ่งทำให้โค้ดสำหรับการดึงข้อมูลย่อยอ่านง่ายขึ้น และยังช่วยให้การค้นหาข้อมูลมีประสิทธิภาพมากขึ้นในบางกรณี
ในบทนี้ เราจะสำรวจ temperatures ซึ่งเป็น DataFrame ที่เก็บข้อมูลอุณหภูมิเฉลี่ยของเมืองต่าง ๆ ทั่วโลก โดยโหลด pandas ไว้เป็น pd แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การจัดการข้อมูลด้วย pandas
คำแนะนำการฝึกหัด
- ดูข้อมูลใน
temperatures - ตั้งค่า index ของ
temperaturesเป็น"city"แล้วกำหนดให้กับtemperatures_ind - ดูข้อมูลใน
temperatures_indแล้วสังเกตว่าต่างจากtemperaturesอย่างไร - รีเซ็ต index ของ
temperatures_indโดยเก็บข้อมูลไว้ - รีเซ็ต index ของ
temperatures_indโดยลบข้อมูลออก
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Look at temperatures
print(____)
# Set the index of temperatures to city
temperatures_ind = ____
# Look at temperatures_ind
print(____)
# Reset the temperatures_ind index, keeping its contents
print(____)
# Reset the temperatures_ind index, dropping its contents
print(____)