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="____"
)