開始使用免費開始

用布林索引做快速統計

回到 animals 資料集。它已載入為由多個字典組成的清單。你將運用剛學到的內容,把這些資料轉換為可用的 DataFrame,接著用布林索引過濾資料,最後再用一點 numpy 小技巧找出一些有趣的動物資訊。

本練習屬於課程

給 MATLAB 使用者的 Python

檢視課程

練習說明

  • 由字典清單 animals 建立 DataFrame animals
  • 建立布林索引 mammals,篩出「Class」為「Mammalia」的紀錄。
  • 建立布林索引 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)))
編輯並執行程式碼