【问题标题】:How to create a postgres table from a pandas dataframe?如何从熊猫数据框创建一个 postgres 表?
【发布时间】:2019-04-18 15:38:26
【问题描述】:

我正在寻找一种从 pandas 数据帧创建 postgres 表的方法,然后直接在 pgAdmin 中读取 postgre 表。 多亏了这个链接,我找到了一种方法:How to write DataFrame to postgres table?

命令是:

from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@host:port/database')
df.to_sql('table_name', engine)

但是,我不知道“table_name”是什么。我必须在我的数据库中创建一个表吗?

感谢您的帮助!

【问题讨论】:

    标签: python database postgresql pandas sqlalchemy


    【解决方案1】:

    如果您指定的名称不存在,则将创建该表。 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html

    【讨论】:

    • 好的,问题是我有一个错误:NameError: name 'bat_prediction_rf' is not defined。我的代码的最后一个符号是 baonotnull_test.to_sql(bat_prediction_rf, engine) 。也许是因为架构。我解释 ;我想在数据库 db 中的架构 p_baobat 本身中创建一个表名“bat_prediction_rf”。我不明白为什么我有这个错误......
    • @Pollux 应该是baonotnull_test.to_sql('bat_prediction_rf', engine)(注意这里'bat_prediction_rf' 是一个字符串)还是bat_prediction_rf 是您代码中其他地方定义的变量?
    • 你是对的,bat_prediction_rf 没有在我的代码中定义,我必须写'bat_prediction_rf'。非常感谢它的工作!很抱歉打扰您。
    • @Pollux 没问题,我很高兴知道它现在对你有用 :-)
    猜你喜欢
    • 2015-03-28
    • 2021-06-08
    • 2021-09-29
    • 1970-01-01
    • 2020-09-21
    • 2018-11-18
    • 2018-03-03
    • 2022-09-24
    • 1970-01-01
    相关资源
    最近更新 更多