将数据加载到 Postgres 数据库
当数据从源系统抽取并转换为适合分析或报表的格式后,接下来就需要将其加载到最终的存储介质中。把清洗后的数据存入 SQL 数据库,便于数据使用者访问并运行查询。在本练习中,您将练习把清洗后的数据加载到 Postgres 数据库。
已导入 sqlalchemy,并可通过 pd 使用 pandas。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="____"
)