python - 自动 PostgreSQL CREATE TABLE 和从 CSV 或 Pandas DataFrame 插入

标签 python r postgresql pandas psycopg2

有谁知道可以将 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/

相关文章:

Python + 请求 + split : What's the fastest/best way to make multiple concurrent 'get' requests?

python - 在 Django 中开始的事务

sql - SQL 长度函数如何处理 unicode 字素?

r - 使用 lubridate 在 R 中修改 POSIXct 格式的日期

r - 各组最近值的总和

postgresql - 连接到 PostgreSQL : Postico and TablePlus DB GUIs can't connect but `psql` in Docker works (FATAL: password authentication failed for user)

sql - 在没有 HAVING 子句的情况下如何改进此查询

python - 使用 Python 测量网络数据

python - 如何将 numpy.int32 转换为 decimal.Decimal

r - 在 ggplot2 中刻面时添加功能区