【问题标题】:ValueError with Pandas - shaped of passed values带有 Pandas 的 ValueError - 传递值的形状
【发布时间】:2015-07-21 21:34:52
【问题描述】:

我正在尝试使用 Pandas 和 PyODBC 从 SQL Server 视图中提取内容并将内容转储到 excel 文件中。

但是,我在转储数据框时遇到错误(我可以打印列和数据框内容):

ValueError: Shape of passed values is (1, 228), indices imply (2, 228)

此论坛上还有其他几个与同一问题相关的问题,但没有讨论从 SQL Server 表中提取。

我不知道是什么导致了这个错误,改变视图以不同的方式投射源列没有效果。

这是我正在使用的python代码:

import pyodbc
import pandas as pd
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=servername;DATABASE=dbname;UID=username;PWD=password')
cursor = cnxn.cursor()
script = """
SELECT * FROM schema.ActiveEnrollmentCount
"""
cursor.execute(script)
columns = [desc[0] for desc in cursor.description]

data = cursor.fetchall()

df = pd.DataFrame(list(data), columns=columns)

writer = pd.ExcelWriter('c:\temp\ActiveEnrollment.xlsx')
df.to_excel(writer, sheet_name='bar')

writer.save()

我试图提取的 2 列都是 3 位整数。

【问题讨论】:

  • 只是要清楚,这个错误来自哪里?从表中拉出或转储数据框?
  • (旁注:你应该像大多数人一样import pandas as pd,这样可以重用和共享代码的sn-ps)
  • 另一个注意事项:您最好使用df = pd.read_sql_query(script, cnxn),而不是手动执行并转换为数据帧
  • @NBartley 更新了我的答案 - 它在转储数据帧时发生。谢谢!
  • @JulienMarrec 谢谢!我从另一个 stackoverflow 帖子中获取了这个示例...

标签: python pandas pyodbc


【解决方案1】:

要从数据库中查询数据,最好使用内置的read_sql_query 函数,而不是手动执行并转换为数据帧。
对于您的示例,这将给出如下内容:

df = pd.read_sql_query(script, cnxn)

有关read_sql/to_sql的更多说明,请参阅docs

【讨论】:

    【解决方案2】:

    这可以将数据从 sqlserver 导出到 excel sheet 。

    import pyodbc
        import pandas as pd
        from openpyxl import Workbook
    
    
        cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                              "Server=WINS2012;"
                              "Database=NameOfDataBase;"
                              "Trusted_Connection=yes;")
    
    
        cursor = cnxn.cursor()
        script = """
        SELECT * FROM ims_employee
        """
        cursor.execute(script)
    
        columns = [desc[0] for desc in cursor.description]
    
        data = cursor.fetchall()
    
        df = pd.read_sql_query(script, cnxn)
    
        writer = pd.ExcelWriter('C:\SqlExcel\Book1.xlsx')
        df.to_excel(writer, sheet_name='bar')
    
        writer.save()
    

    【讨论】:

    • 通过上述示例的帮助,这对我有用
    猜你喜欢
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    相关资源
    最近更新 更多