切片索引值
切片可用 first:last 語法,選取物件中一段連續的元素。DataFrame 可以依索引值或依列/欄編號進行切片;我們先從前者開始。這需要在 .loc[] 方法中進行切片。
與對列表做切片相比,有幾點要注意。
- 只有在索引已排序(使用
.sort_index())時,才能對索引做切片。 - 若要在最外層切片,
first和last可以是字串。 - 若要在內層切片,
first和last應該是元組(tuple)。 - 如果只把單一切片傳給
.loc[],會對列進行切片。
已將 pandas 載入為 pd。temperatures_ind 的索引包含國家與城市,並已可使用。
本練習屬於課程
使用 pandas 進行資料操作
練習說明
- 將
temperatures_ind的索引排序。 - 使用
.loc[]切片取得以下子集:- 從 Pakistan 到 Philippines。
- 從 Lahore 到 Manila。(這會回傳沒有意義的結果。)
- 從 Pakistan, Lahore 到 Philippines, Manila。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Sort the index of temperatures_ind
temperatures_srt = ____
# Subset rows from Pakistan to Philippines
print(____)
# Try to subset rows from Lahore to Manila
print(____)
# Subset rows from Pakistan, Lahore to Philippines, Manila
print(____)