python - 将新列(Pandas Dataframe)添加到Postgresql表中

时间:2018-06-12 08:34:49

标签: python postgresql pandas dataframe

如何在exisitng postgresql数据库表中动态创建新列并将Pandas Dataframe填充到其中?

直到我用过:

from sqlalchemy import create_engine

engine=create_engine('postgresql+psycopg2://postgres@localhost:5432/db_name')

df.to_sql('table_name', engine,if_exists='append',index=False)

其中df =已经创建了熊猫数据帧

此外,我在Dataframe中有两列,我想在数据库表中为它们创建单独的列。

提前致谢!

1 个答案:

答案 0 :(得分:0)

我认为你可以使用psycopg2

这样做
import psycopg2
conn = psycopg2.connect(database=db_name, user=user_name, password=pass_word, host="127.0.0.1", port="5432")
cur = conn.cursor()
sql = "ALTER TABLE table_name ADD COLUMN new_column_name data_type;"
cur.execute(sql)
conn.commit()
cur.close()

它允许您通过python脚本直接编写sql命令。 有关详细信息,请参阅this docs