【问题标题】:Python3: Connecting into postgresql database with Python... how do I get resulting query to return as rows in a pandas dataframe?Python3:使用 Python 连接到 postgresql 数据库...如何让结果查询作为 pandas 数据框中的行返回?
【发布时间】:2019-09-10 03:37:34
【问题描述】:

我已通过 Jupyter Notebook 将我的 python 连接到我的本地 postgresql 数据库。我能够成功运行 SELECT 查询并从我的表中提取数据。

但是,我想将我的 postgresql 表中的数据行显示为数据框,而不是我目前拥有的数据。

下面是我的代码:

conn = psycopg2.connect("dbname=juke user=postgres")

cur = conn.cursor()
cur.execute('SELECT * FROM albums')

for i in cur:
    print(i)

这是我的代码输出:

如何让输出显示为数据框中的行?

我从人们分享的推荐重复帖子中查看并尝试了一系列不同的可能解决方案。不幸的是,他们都没有工作。

【问题讨论】:

标签: python sql dataframe select connect


【解决方案1】:

使用熊猫创建数据框 - https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql_query.html:

import pandas as pd
conn = psycopg2.connect("dbname=juke user=postgres")
df = pd.read_sql_query("SELECT * FROM albums", conn)
df.head()

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 2019-10-19
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    相关资源
    最近更新 更多