開始使用免費開始

使用 .loc[] 進行子集篩選

索引最強大的功能就是 .loc[]:它是一種接受索引值的子集篩選方法。當你只傳入一個引數時,會擷取列的子集。

使用 .loc[] 的子集篩選,通常比用方括號的標準寫法更容易閱讀,也讓你的程式碼更容易維護。

已載入 pandas 並命名為 pdtemperaturestemperatures_ind 已可使用;其中 temperatures_indcity 作為索引。

本練習屬於課程

使用 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[____])
編輯並執行程式碼