在将数据帧写入postgres表时遇到一些问题。
接下来需要做的是:我需要将pandas df保存为Postgres表,明天创建新的pandas df时(前一天的列可以比df多或少),我需要删除昨天保存的Postgres表并在Postgres中编写今天的表格。由于列数不一致,因此无法为该表编写任何DDL。
接下来我要尝试的是
import pandas as pd
import psycopg2
import sqlalchemy
from sqlalchemy import *
conn = psycopg2.connect("host=localhost dbname=postgres user=postgres password=passforpostgre")
cur = conn.cursor()
engine = sqlalchemy.create_engine('postgresql://passforpostgre@localhost')
df = pd.DataFrame([['user1','adress1'], ['user2','adress2'], ['user3','adress3']], columns=["name", "address"])
df.to_sql('test_table', con=engine, if_exists='append')
sqlalchemy.delete('df3')
# cur.execute('DROP TABLE "%s";' % 'test_table')
然后我放一列(因为我可能会有另一天)
df2.drop('address', 1)
d2.to_sql('test_table', con=engine, if_exists='append')
但是,无论我使用delete还是DROP TABLE都没有关系,不会从架构中删除表。但是我无法打开它,只是查询了很长时间...
有人可以建议我最合适的方法吗?
谢谢