設定與移除索引
pandas 允許你將欄位指定為「索引」。這樣在進行子集擷取時,程式碼會更乾淨,而且在某些情況下也能更有效率地查找。
在本章中,你會使用 temperatures,這是一個包含世界各城市平均氣溫的 DataFrame。pandas 已載入為 pd。
本練習屬於課程
使用 pandas 進行資料操作
練習說明
- 檢視
temperatures。 - 將
temperatures的索引設為"city",指定給temperatures_ind。 - 檢視
temperatures_ind。它與temperatures有何不同? - 重設
temperatures_ind的索引,並保留其內容。 - 重設
temperatures_ind的索引,並捨棄其內容。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Look at temperatures
print(____)
# Set the index of temperatures to city
temperatures_ind = ____
# Look at temperatures_ind
print(____)
# Reset the temperatures_ind index, keeping its contents
print(____)
# Reset the temperatures_ind index, dropping its contents
print(____)