【问题标题】:Pandas read_sql columns not working when using index_col - returns all columns insteadPandas read_sql 列在使用 index_col 时不起作用 - 而是返回所有列
【发布时间】:2016-03-11 10:20:27
【问题描述】:

我正在使用pandas.read_sql() 命令从我的 postgresql 数据库中获取数据。 SQL 查询通常由许多列创建,我只想使用一列作为索引从中获取特定列。 像这样创建一个示例表test_table

column1 column2 column3
1       2       3
2       4       6
3       6       9

我尝试使用pandas.read_sql() 中的index_colcolumns 参数来获取column1 作为索引和column2 作为数据(并忽略column3!)。但它总是返回整个表。同样在写columns=['column1', 'column2'] 时没有任何变化......

我正在使用 python 2.7.6 和 pandas 0.17.1 - 感谢您的帮助!

示例代码:

import pandas
import psycopg2
import sqlalchemy


def connect():
    connString = (
        "dbname=test_db "
        "host=localhost "
        "port=5432 "
        "user=postgres "
        "password=password"
    )
    return psycopg2.connect(connString)

engine = sqlalchemy.create_engine(
            'postgresql://',
            creator=connect)
sql = (
    'SELECT '
    'column1, '
    'column2, '
    'column3 '
    'FROM test_table'
)
data = pandas.read_sql(
    sql,
    engine,
    index_col=['column1'],
    columns=['column2'])
print(data)

【问题讨论】:

  • 您为什么不想更改您的“选择”查询?我猜你想改用pandas.read_sql_query()
  • sql 查询应该只构建一次,然后由不同的函数使用,从中选择特定的列。我没有使用read_sql_query(),因为它没有columns 参数(这并没有真正做我现在想要的) - 我的代码read_sql()read_sql_query() 没有区别......

标签: python postgresql pandas


【解决方案1】:

我认为columns 参数对您不起作用,因为您使用的是 sql 语句而不是为它提供您的表名。

如熊猫网站所述:

columns : 列表,默认值:None 要从 sql 中选择的列名列表 表格(仅在读取表格时使用)。

因此,我认为如果你尝试:

pandas.read_sql('test_table', engine, index_col=['column1'], columns=['column2'])

columns 参数实际上会起作用。

【讨论】:

  • 不支持sql语句很可惜
猜你喜欢
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 2017-01-24
  • 2021-12-16
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
相关资源
最近更新 更多