開始使用免費開始

操作 DateTime 欄位

pandas 預設會把日期時間欄位載入為 object 型別。文字形式的日期對時間序列分析幫助不大,所以你需要把這些欄位轉換成 datetime 型別。這種型別能讓你更彈性地處理 pandas 的日期,並從中擷取有用的特徵。

另一個股票資料集(這次是 Apple)已載入為 apple。

本練習屬於課程

Python 中的異常偵測

檢視課程

練習說明

  • 將 apple 的 Date 欄位轉換成 datetime 欄位。
  • 擷取星期幾,並存成名為 day_of_week 的新欄位。
  • 擷取月份數字,並存成名為 month 的新欄位。
  • 擷取每月中的日期,並存成名為 day_of_month 的新欄位。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Convert the Date column to DateTime
apple['Date'] = ____

# Create a column for the day of the week
apple['day_of_week'] = ____

# Create a column for the month
apple['month'] = ____

# Create a column for the day of the month
apple['day_of_month'] = ____

print(apple[['day_of_week', 'month', 'day_of_month']])
編輯並執行程式碼