列選取:loc[] 與 iloc[]
在處理 DataFrame 時,很重要的一部分是從資料集中定位特定的項目。你可以用兩種方式選取列:
- 依據某個欄(特徵)的特定值。
- 依據列的索引(index)。在這個練習中,我們會聚焦在第二種方式。
如果你先前用過 pandas,你應該熟悉索引器 .loc 與 .iloc,分別代表「label 位置」與「索引位置」。大多數情況下,索引會和 DataFrame 中每一列的位置相同(例如:索引為 13 的列就是第 14 筆)。
雖然這兩個函式都能完成相同的任務,我們想比較在速度上哪一個更有效率。
本練習屬於課程
使用 pandas 撰寫高效程式碼
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define the range of rows to select: row_nums
row_nums = range(0, 1000)
# Select the rows using .loc[] and row_nums and record the time before and after
loc_start_time = time.time()
rows = poker_hands.____[____]
loc_end_time = ___
# Print the time it took to select the rows using .loc[]
print("Time using .loc[]: {} sec".format(___ - ___))