pandas read_sql Imports NULLs as 0s

倖福魔咒の 提交于 2019-12-13 03:23:42

问题


Edit: Apparently my connection (PYODBC) is reading in the NULLs as 0s. I'd like to correct this on a "higher" level as I'll be reading in lots of SQL files. I can't find anything in the documentation to prevent this. Any suggestions?

I am importing a SQL file/query as a string and then using pd.read_sql to query my database. In SQL Server I can do calculations between NULL values which results in a NULL value, however, in Python, this errors out my script.

Query ran in SQL Server:

SELECT PurchaseOrderID, POTotalQtyVouched, NewColumn = PurchaseOrderID/POTotalQtyVouched FROM #POQtys;

Here is my desired output after running the query (which works in SQL Server):

PurchaseOrderID    POTotalQtyVouched   NewColumn
NULL               NULL                NULL
007004             8                   875.5
008017             21                  381.761904761905
008478             NULL                NULL

Running the query in Python:

query = '''
...
[Other code defining #POQTYs]
...
SELECT PurchaseOrderID, POTotalQtyVouched, NewColumn = PurchaseOrderID/POTotalQtyVouched FROM #POQtys;

'''
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
                      'Server=MSS-SL-SQL;'
                      'Database=TRACE DB;'
                      'Trusted_Connection=yes;')

df = pd.read_sql(query, conn)

Error in Python:

DataError: ('22012', '[22012] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Divide by zero error encountered. (8134) (SQLFetch)')

来源:https://stackoverflow.com/questions/58107175/pandas-read-sql-imports-nulls-as-0s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!