เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การใช้ 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)))
แก้ไขและรันโค้ด