開始使用免費開始

使用 SQL 選取欄位

資料集常包含分析不需要的欄位,data.db 中的 weather 資料表就是一例。有些欄位(例如海拔)是多餘的,因為所有觀測都在同一地點發生;也有些欄位包含你不感興趣的變數。建立資料庫引擎之後,你將撰寫查詢,只 SELECT 日期與氣溫相關的欄位,並將查詢與引擎一併傳入 read_sql(),建立一個含有最高與最低氣溫讀數的 dataframe。

pandas 已以 pd 載入,create_engine() 已從 sqlalchemy 匯入。

注意:SQL 測試器對欄位位置相當嚴格,請依指定順序選取欄位。

本練習屬於課程

使用 pandas 的精實資料導入

檢視課程

練習說明

  • data.db 建立一個資料庫引擎。
  • 撰寫一個 SQL 查詢,從 weather 資料表中 SELECT datetmaxtmin 欄位。
  • 將查詢與引擎傳入 read_sql() 以建立 dataframe,並把結果指派給 temperatures

動手互動練習

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

# Create database engine for data.db
engine = ____

# Write query to get date, tmax, and tmin from weather
query = """
SELECT ____, 
       ____, 
       ____
  FROM ____;
"""

# Make a dataframe by passing query and engine to read_sql()
temperatures = ____

# View the resulting dataframe
print(temperatures)
編輯並執行程式碼