从 CSV 或 Pandas DataFrame 自动 PostgreSQL CREATE TABLE 和 INSERT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20997283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Automatic PostgreSQL CREATE TABLE and INSERT from CSV or Pandas DataFrame
提问by Tommy O'Dell
Does anyone know of some Pythonpackage or function that can upload a Pandas DataFrame(or simply a .csv) to a PostgreSQL table, even if the table doesn't yet exist?
有谁知道一些Python可以将 Pandas DataFrame(或只是 a .csv)上传到 PostgreSQL 表的包或函数,即使该表尚不存在?
(i.e. it runs a CREATE TABLE with the appropriate column names and columns types based on a mapping between the python data types and closest equivalents in PostgreSQL)
(即,它基于 Python 数据类型和 PostgreSQL 中最接近的等价物之间的映射运行具有适当列名和列类型的 CREATE TABLE)
In R, I use the ROraclepackage which provides a dbWriteTablefunction that does what I've described above. (see docs here)
在 中R,我使用的ROracle包提供了一个dbWriteTable执行我上面描述的功能的函数。(请参阅此处的文档)
回答by joris
Since pandas 0.14, the sql functions also support postgresql (via SQLAlchemy, so all database flavors supported by SQLAlchemy work). So you can simply use to_sqlto write a pandas DataFrame to a PostgreSQL database:
从 pandas 0.14 开始,sql 函数也支持 postgresql(通过 SQLAlchemy,所以 SQLAlchemy 支持的所有数据库风格都可以工作)。因此,您可以简单地使用to_sql将 Pandas DataFrame 写入 PostgreSQL 数据库:
import pandas as pd
from sqlalchemy import create_engine
import psycopg2
engine = create_engine('postgresql://scott:tiger@localhost:5432/mydatabase')
df.to_sql("table_name", engine)
See the docs: http://pandas.pydata.org/pandas-docs/stable/io.html#sql-queries
请参阅文档:http: //pandas.pydata.org/pandas-docs/stable/io.html#sql-queries
If you have an older version of pandas (< 0.14), see this question:How to write DataFrame to postgres table?
如果您有旧版本的Pandas (< 0.14),请参阅此问题:如何将 DataFrame 写入 postgres 表?
回答by user531525
They just made a package for this. https://gist.github.com/catawbasam/3164289Not sure how well it works.
他们只是为此做了一个包裹。https://gist.github.com/catawbasam/3164289不确定它的效果如何。

