將資料載入 Postgres 資料庫
當你已經從來源系統擷取資料,並完成轉換以符合分析或報表的需求後,下一步就是將資料載入最終的儲存介質。把清理過的資料存入 SQL 資料庫,可以讓資料使用者更容易存取並執行查詢。在這個例子中,你將練習把清理過的資料載入 Postgres 資料庫。
已匯入 sqlalchemy,而 pandas 以 pd 可用。cleaned_testing_scores DataFrame 的前幾列如下:
street_address city math_score ... best_score
01M539 111 Columbia Street Manhattan 657.0 Math
02M545 350 Grand Street Manhattan 613.0 Math
01M292 220 Henry Street Manhattan 410.0 Math
本練習屬於課程
使用 Python 的 ETL 與 ELT
練習說明
- 更新連線字串以寫入
schools資料庫,並使用sqlalchemy建立連線物件。 - 使用
pandas將cleaned_testing_scoresDataFrame 寫入schools資料庫中的scores資料表。 - 如果資料表已經有資料,請以目前的 DataFrame 取代既有內容。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Update the connection string, create the connection object to the schools database
db_engine = sqlalchemy.____("postgresql+psycopg2://repl:password@localhost:5432/____")
# Write the DataFrame to the scores table
cleaned_testing_scores.____(
name="____",
con=db_engine,
index=False,
if_exists="____"
)