開始使用免費開始

帶條件的時間戳記資料串列生成式

做得好!你已經成功從 pandas DataFrame 中擷取到重點資料——時間。接下來我們再加上一個條件,進一步指定要挑選哪些項目。

在這個練習中,你會使用串列生成式,從含時間戳記的 Twitter 資料中擷取時間。你將在串列生成式中加入條件判斷,讓你只選出 entry[17:19] 等於 '19' 的時間。pandas 套件已以 pd 名稱匯入,檔案 'tweets.csv' 也已讀入為 DataFrame df 供你使用。

本練習屬於課程

Python 工具箱

檢視課程

練習說明

  • df 取出欄位 'created_at',並指定給 tweet_time
  • 建立一個串列生成式,從 tweet_time 的每一列字串中擷取時間。每一列是代表時間戳記的字串,你需要存取該字串的「第 12 到第 19 個字元」來擷取時間。請使用 entry 作為「迭代變數」,並將結果指定給 tweet_clock_time。此外,加入條件判斷,檢查 entry[17:19] 是否等於 '19'

動手互動練習

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

# Extract the created_at column from df: tweet_time
tweet_time = ____

# Extract the clock time: tweet_clock_time
tweet_clock_time = [____ for ____ in ____ if ____ == ____]

# Print the extracted times
print(tweet_clock_time)
編輯並執行程式碼