【问题标题】:executing and reading a Microsoft SQL query into a pandas dataframe with Columns Names执行 Microsoft SQL 查询并将其读取到带有列名称的 pandas 数据框中
【发布时间】:2018-02-05 14:48:15
【问题描述】:

我正在尝试执行查询,然后将其放入数据框中。由于某种原因,它只加载第 0 列。整个结果集被加载到该列中。

这就是我正在做的事情

conn = pyodbc.connect("connection info")
cursor = conn.cursor()
cursor.execute = "sql statement"
names = [ x[0] for x in cursor.description]
rows = cursor.fetchall()
df = pd.DataFrame(rows, columns = names)

我收到此错误。

ValueError: Shape of passed values is (1, 421), indices imply (5, 421)

假设是 5 列,但是当我在没有“列 = 名称”的情况下运行它并且数据框返回一列时。在此列中,它存储来自 sql 查询的 5 列的整个数据集。

这是我在没有“列名”的情况下运行结果集时的示例:

(9026461, 875, 110, Decimal('1.08'), 3100)

【问题讨论】:

  • 你试过pd.read_sql_query()吗?
  • 是的,我尝试了 pd.read_sql_query(),但是这不起作用,因为我的 sql 语句有 where 子句。好吧,我无法让它工作。执行终于检索到了结果,但由于某种原因,我无法在包含所有列的数据帧中获得结果集……太难了!
  • 无论是否有 where 子句,它都应该工作。它应该全部包含在sql 参数中。
  • 你知道为什么数据框没有创建列吗?这基本上就是我正在做的gist.github.com/mvaz/2006493
  • 如果你执行 fetchone() 并查看它,你会得到什么?

标签: python pandas pyodbc


【解决方案1】:

这最终适用于以下内容:

 engine = create_engine('mssql+pyodbc://serverName/DatabaseName?  driver=SQL+Server+Native+Client+11.0')
 connection = engine.connect()

 resultSet = connection.execute("select column1, column2 from ....")
 df = pd.DataFrame(resultSet.fetchall())
 df.columns = resultSet .keys()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-30
    • 2019-10-31
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2018-02-02
    • 1970-01-01
    相关资源
    最近更新 更多