使用 .loc[] 進行子集篩選
索引最強大的功能就是 .loc[]:它是一種接受索引值的子集篩選方法。當你只傳入一個引數時,會擷取列的子集。
使用 .loc[] 的子集篩選,通常比用方括號的標準寫法更容易閱讀,也讓你的程式碼更容易維護。
已載入 pandas 並命名為 pd。temperatures 與 temperatures_ind 已可使用;其中 temperatures_ind 以 city 作為索引。
本練習屬於課程
使用 pandas 進行資料操作
練習說明
- 建立名為
cities的清單,內容包含 "London" 與 "Paris"。 - 使用
[]子集篩選,將temperatures只保留city欄位值出現在cities清單中的列。 - 使用
.loc[]子集篩選,將temperatures_ind只保留城市在cities清單中的列。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Make a list of cities to subset on
cities = ["____", "____"]
# Subset temperatures using square brackets
print(temperatures[____])
# Subset temperatures_ind using .loc[]
print(temperatures_ind.loc[____])