การโหลดข้อมูลเข้าฐานข้อมูล Postgres
หลังจากดึงข้อมูลออกจากระบบต้นทางและแปลงข้อมูลให้เหมาะสมกับการใช้งานด้านการวิเคราะห์หรือการจัดทำรายงานแล้ว ขั้นตอนต่อไปคือการโหลดข้อมูลเข้าสู่สื่อจัดเก็บข้อมูลขั้นสุดท้าย การจัดเก็บข้อมูลที่ทำความสะอาดแล้วไว้ในฐานข้อมูล SQL ช่วยให้ผู้ใช้ข้อมูลเข้าถึงและรันคิวรีได้อย่างสะดวก ในตัวอย่างนี้ คุณจะได้ฝึกโหลดข้อมูลที่ทำความสะอาดแล้วเข้าสู่ฐานข้อมูล Postgres
มีการนำเข้า sqlalchemy มาให้แล้ว และ pandas พร้อมใช้งานในชื่อ pd แถวแรก ๆ ของ DataFrame ชื่อ cleaned_testing_scores แสดงไว้ด้านล่างนี้:
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
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
ETL and ELT ใน Python
คำแนะนำการฝึกหัด
- อัปเดต connection string ให้เขียนข้อมูลลงฐานข้อมูล
schoolsแล้วสร้าง connection object โดยใช้sqlalchemy - ใช้
pandasเขียน DataFrame ชื่อcleaned_testing_scoresลงในตารางscoresของฐานข้อมูลschools - หากตารางมีข้อมูลอยู่แล้ว ให้แทนที่ค่าเดิมด้วย 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="____"
)