將月資料轉為週資料
你在影片中已經學過如何使用 .reindex(),把既有的時間序列調整為不同頻率的 DateTimeIndex。
現在來練習這個方法:先建立月資料,然後把它轉換為週頻率,同時套用不同的填補邏輯選項。
本練習屬於課程
Manipulating Time Series Data in Python
練習說明
我們已經替你匯入 pandas 並命名為 pd,也定義了 start 與 end 日期。
- 使用
pd.date_range搭配start、end與頻率別名'M'建立monthly_dates。 - 建立並列印
pd.Series物件monthly,將清單[1, 2]作為data參數,並以monthly_dates作為index。 - 使用
pd.date_range搭配start、end與頻率別名'W'建立weekly_dates。 - 對
monthly連續呼叫三次.reindex():先不加任何選項,接著使用bfill,最後使用ffill,並各自print()輸出結果。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Set start and end dates
start = '2016-1-1'
end = '2016-2-29'
# Create monthly_dates here
monthly_dates = ____
# Create and print monthly here
monthly = ____
print(____)
# Create weekly_dates here
weekly_dates = ____
# Print monthly, reindexed using weekly_dates
print(____)
print(____)
print(____)