欄位選取:.iloc[] 與欄名比較
在上一個練習中,你看到了 .loc[] 和 .iloc[] 函式如何用來依索引定位 DataFrame 的特定「列」。結果發現,針對這個任務,.iloc[] 的效能快上不少(約 2 倍)!
另一個重要任務是找出在選取 DataFrame 目標「特徵(欄)」時,哪個方法比較快。這個練習中,我們將比較以下兩種作法:
- 使用索引定位器
.iloc() - 使用欄位名稱 雖然兩種方式都能完成相同的事,我們關心的是哪一種在速度上更有效率。
在這個練習中,你會繼續使用儲存在 poker_hands 中的撲克牌資料。先花一點時間在主控台呼叫 poker_hands.head(),看看這個 DataFrame 的結構吧!
本練習屬於課程
使用 pandas 撰寫高效程式碼
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Use .iloc to select the first, fourth, fifth, seventh and eighth column and record the times before and after
iloc_start_time = ___
cols = poker_hands.___[___,[0,3,___,___,___]]
iloc_end_time = ___
# Print the time it took
print("Time using .iloc[] : {} sec".format(___ - ___))