问题
I'm trying to use Pandas and PyODBC to pull from a SQL Server View and dump the contents to an excel file.
However, I'm getting the error when dumping the data frame (I can print the colums and dataframe content):
ValueError: Shape of passed values is (1, 228), indices imply (2, 228)
There are several other issues on this forum pertaining to the same issue, but none discuss pulling from a SQL Server table.
I can't figure out what is causing this error, and altering the view to cast the source columns differently has no effect.
Here is the python code i'm using:
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()
The 2 columns I'm trying to pull are both 3-digit integers.
回答1:
To query data from a database, you can better use the built-in read_sql_query function instead of doing the execute and converting to dataframe manually.
For your example, this would give something like:
df = pd.read_sql_query(script, cnxn)
See the docs for more explanation on read_sql
/to_sql
.
回答2:
This worked from to export data from sqlserver to 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()
来源:https://stackoverflow.com/questions/31550031/valueerror-with-pandas-shaped-of-passed-values