python pandas, sqlalchemy to_sql 데이터 중복 처리 하는 방법
조회수 731회
python3 에서 pandas와 sqlalchemy를 이용해서 DB에 데이터를 저장하고 있습니다.
기존에 데이터를 읽은 후 새로운 DF의 데이터와 groupby 후 sum 값을 if_exists='append' 하는데 데이터가 중복되어 장애가 납니다 순서는 아래와 같습니다.
# 새로운 DF와 기존의 DF를 concat 후 groupby하여 cnt값을 더합니다.
df_new = someDataFrame~~
df_old = pd.read_sql_query("SELECT * FROM tableName", engine)
df_concat = pd.concat([df_new, df_old], ignore_index=True)
df_res = df_concat.groupby(by=[pk list])
df_res = df_res['cnt'].sum().reset_index()
with engine.connect().execution_options(autocommit=True) as conn:
conn.execute(text("""DELETE FROM tableName"""))
conn.close()
df_res.to_sql(
schema='someSchema',
name='tableName',
con=engine, if_exists='append', index=False, index_label=None, chunksize=10000
)
이렇게 진행했을 때 제 예상은 df_res에서 새로운 데이터와 기존의 데이터를 계산을 끝내고 기존 데이터를 Delete하여 삭제한 후 to_sql로 밀어 넣는것입니다. 근데 delete 후 autocommit을 했는데도 PK 중복 에러가 발생하네요... 커밋 시점이 잘 못된걸까요?
어떤식으로 append해야할지 조언 부탁드립니다.
댓글 입력