Postgres 데이터베이스로 데이터 적재하기
소스 시스템에서 데이터를 추출하고 분석이나 보고 목적에 맞게 변환했다면, 이제 최종 저장소로 데이터를 적재할 차례예요. 정제된 데이터를 SQL 데이터베이스에 저장하면 데이터 사용자가 쉽게 접근하고 쿼리를 실행할 수 있어요. 이 예제에서는 정제된 데이터를 Postgres 데이터베이스에 적재하는 연습을 해 봅니다.
sqlalchemy는 이미 임포트되어 있고, pandas는 pd로 사용할 수 있어요. 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
이 연습은 강의의 일부입니다
Python으로 ETL과 ELT
연습 안내
- 연결 문자열을
schools데이터베이스로 쓰도록 업데이트하고,sqlalchemy로 연결 객체를 생성하세요. pandas를 사용해cleaned_testing_scores데이터프레임을schools데이터베이스의scores테이블에 기록하세요.- 테이블에 이미 데이터가 있다면, 현재 데이터프레임의 값으로 교체되도록 설정하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# 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="____"
)