Pandas 與 SQL 查詢的 Hello World!
在這裡,你將運用 pandas 的威力,只用一行 Python 程式碼,就把 SQL 查詢的結果寫入一個 DataFrame!
你會先匯入 pandas,並建立 SQLite 資料庫 'Chinook.sqlite' 的引擎。接著,你會查詢資料庫,從 Album 資料表選取所有記錄。
回想一下,為了從 Northwind 資料庫的 Orders 資料表選取所有記錄,Hugo 執行了以下指令:
df = pd.read_sql_query("SELECT * FROM Orders", engine)
本練習屬於課程
Python 資料匯入入門
練習說明
- 以別名
pd匯入pandas套件。 - 使用
create_engine()函式,為 SQLite 資料庫Chinook.sqlite建立引擎,並指定給變數engine。 - 使用
pandas的read_sql_query()函式,將以下查詢的結果指定給變數df,也就是從資料表Album中選取所有(all)記錄(select from)。 - 其餘的程式碼會用來確認:用這個方法建立的 DataFrame,與你先前學到的方法所建立的結果相同。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import packages
from sqlalchemy import create_engine
import ____ as ____
# Create engine: engine
# Execute query and store records in DataFrame: df
df = pd.read_sql_query(____, ____)
# Print head of DataFrame
print(df.head())
# Open engine in context manager and store query result in df1
with engine.connect() as con:
rs = con.execute("SELECT * FROM Album")
df1 = pd.DataFrame(rs.fetchall())
df1.columns = rs.keys()
# Confirm that both methods yield the same result
print(df.equals(df1))