Return Pandas 来自 PostgreSQL 使用 sqlalchemy 查询的数据帧

Return Pandas dataframe from PostgreSQL query with sqlalchemy

我想查询 PostgreSQL 数据库,return 输出为 Pandas 数据框。

我使用 'SqlAlchemy' 创建了一个到数据库的连接:

from sqlalchemy import create_engine
engine = create_engine('postgresql://user@localhost:5432/mydb')

我将 Pandas 数据帧写入数据库 table:

i=pd.read_csv(path)
i.to_sql('Stat_Table',engine,if_exists='replace')

基于 docs,看起来 pd.read_sql_query() 应该接受 SQLAlchemy 引擎:

a=pd.read_sql_query('select * from Stat_Table',con=engine)

但是它抛出一个错误:

ProgrammingError: (ProgrammingError) relation "stat_table" does not exist

我正在使用 Pandas 版本 0.14.1。

正确的做法是什么?

错误消息告诉您 table 名为:

stat_table

不存在(关系在postgres中是table)。因此,您当然不能从中提取 select 行。执行后检查你的数据库:

i.to_sql('Stat_Table',engine,if_exists='replace')

并查看是否在您的数据库中创建了一个 table 名称。

当我使用你的读语句时:

df = pd.read_sql_query('select * from Stat_Table',con=engine)

我从 postgres 数据库取回数据,所以没有任何问题。

您被 PostgreSQL 的大小写(不)敏感性问题所困扰。如果您在查询中引用 table 名称,它将起作用:

df = pd.read_sql_query('select * from "Stat_Table"',con=engine)

但就我个人而言,我建议始终使用小写 table 名称(和列名称),在将 table 写入数据库时​​也是如此,以防止出现此类问题。


来自 PostgreSQL 文档 (http://www.postgresql.org/docs/8.0/static/sql-syntax.html#SQL-SYNTAX-IDENTIFIERS):

Quoting an identifier also makes it case-sensitive, whereas unquoted names are always folded to lower case

再解释一下:您已经将名称为 Stat_Table 的 table 写入数据库(并且 sqlalchemy 将引用此名称,因此它将被写为 "Stat_Table"在 postgres 数据库中)。在执行查询 'select * from Stat_Table' 时,未加引号的 table 名称将转换为小写 stat_table,因此您会收到一条消息,指出未找到此 table。

参见例如 Are PostgreSQL column names case-sensitive?

读取下面给出的 pandas 中的 postgres sql 数据和图像 link

import psycopg2 as pg
import pandas.io.sql as psql
connection = pg.connect("host=localhost dbname=kinder user=your_username password=your_password")
dataframe = psql.read_sql('SELECT * FROM product_product', connection)
product_category = psql.read_sql_query('select * from product_category', connection)

https://i.stack.imgur.com/1bege.png

晚会来晚了,但给你一个完整的例子:

import pandas as pd
import psycopg2 as pg

engine = pg.connect("dbname='my_db_name' user='pguser' host='127.0.0.1' port='15432' password='pgpassword'")
df = pd.read_sql('select * from Stat_Table', con=engine)

您需要运行以下内容来安装 ubuntu 的依赖项:

pip install pandas psycopg2-binary SQLAlchemy

Pandas 有关该主题的文档 here

导入 sqlalchemy
导入 psycopg2

引擎 = sqlalchemy.create_engine('postgresql://user@localhost:5432/mydb')

您必须指定 架构和 table
df = pd.read_sql_query("""select * 来自 "dvd-rental".film""", con=engine)