การใช้ Boolean indexing เพื่อดูสถิติเบื้องต้น
กลับมาที่ชุดข้อมูล animals กันอีกครั้ง ซึ่งโหลดไว้เป็น list of dictionaries คราวนี้จะนำทุกสิ่งที่เรียนมาประยุกต์ใช้ด้วยการแปลงข้อมูลให้กลายเป็น DataFrame กรองข้อมูลด้วย Boolean indexing แล้วใช้ numpy เพื่อค้นหาข้อมูลสถิติที่น่าสนใจเกี่ยวกับสัตว์
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python สำหรับผู้ใช้ MATLAB
คำแนะนำการฝึกหัด
- สร้าง DataFrame ชื่อ
animalsจาก list of dictionaries ที่ชื่อanimals - สร้าง Boolean index ชื่อ
mammalsโดยค้นหาแถวที่ "Class" มีค่าเป็น "Mammalia" - สร้าง Boolean index ชื่อ
birdsโดยค้นหาแถวที่ "Class" มีค่าเป็น "Aves" - ใช้
numpyคำนวณค่าเฉลี่ยของคอลัมน์ "Litter/Clutch size" สำหรับสัตว์เลี้ยงลูกด้วยนมและนก
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Create a DataFrame from animals
animals = pd.____(animals)
# Create Boolean indices for mammals and birds
mammals = animals['Class']=='____'
birds = animals['Class']=='____'
# Use numpy and the Boolean indices to determine mean Litter/Clutch size
litter = np.____(animals[mammals]['Litter/Clutch size'])
clutch = np.____(animals[____]['Litter/Clutch size'])
# Print the average Litter/Clutch size of each class
print('Mammals have an average of {} offspring in each litter.'.format(round(litter, 2)))
print('The average clutch size in a single brood is {} eggs.'.format(round(clutch, 2)))