切片處理時間序列
切片對時間序列特別實用,因為你常常需要依日期區間來過濾資料。請先把 date 欄加入索引,然後用 .loc[] 來做子集篩選。重點是日期要使用 ISO 8601 格式,也就是年-月-日用 "yyyy-mm-dd",年-月用 "yyyy-mm",年份用 "yyyy"。
回想第 1 章,你可以用邏輯運算子(例如 &)把多個布林條件結合在一起。若要在同一行程式碼完成,請在每個條件外加上括號 ()。
pandas 已以 pd 載入,且 temperatures 沒有索引、可直接使用。
本練習屬於課程
使用 pandas 進行資料操作
練習說明
- 請使用布林條件(不要用
.isin()或.loc[]),並以完整日期"yyyy-mm-dd",篩選temperatures中date欄位落在 2010 與 2011 年的列,並列印結果。 - 將
temperatures的索引設為date欄,並加以排序。 - 使用
.loc[]篩選temperatures_ind中 2010 與 2011 年的列。 - 使用
.loc[]篩選temperatures_ind中從 August 2010 到 February 2011 的列。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Use Boolean conditions to subset temperatures for rows in 2010 and 2011
temperatures_bool = ____[(____ >= ____) & (____ <= ____)]
print(temperatures_bool)
# Set date as the index and sort the index
temperatures_ind = temperatures.____.____
# Use .loc[] to subset temperatures_ind for rows in 2010 and 2011
print(____)
# Use .loc[] to subset temperatures_ind for rows from Aug 2010 to Feb 2011
print(____)