有谁知道可以将 Pandas DataFrame
(或简单的 .csv
)上传到 PostgreSQL 表的某些 Python
包或函数, 即使表还不存在?
(即,它根据 Python 数据类型和 PostgreSQL 中最接近的等效项之间的映射,使用适当的列名和列类型运行 CREATE TABLE)
在 R
中,我使用 ROracle
包,它提供了一个 dbWriteTable
函数来执行我上面描述的操作。 (参见文档 here)
最佳答案
从 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)
查看文档:http://pandas.pydata.org/pandas-docs/stable/io.html#sql-queries
如果您有旧版本的 pandas (< 0.14),请参阅此问题:How to write DataFrame to postgres table?
关于python - 自动 PostgreSQL CREATE TABLE 和从 CSV 或 Pandas DataFrame 插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20997283/