0

在 Python 2.7 中,我使用以下命令连接到外部数据源:

import pypyodbc
import pandas as pd
import datetime
import csv
import boto3
import os

# Connect to the DataSource
conn = pypyodbc.connect("DSN = FAKE DATA SOURCE; UID=FAKEID; PWD=FAKEPASSWORD")

# Specify the query we're going to run on it
script = ("SELECT * FROM table")

# Create a dataframe from the above query
df = pd.read_sql_query(script, conn)

我收到以下错误:

C:\Python27\python.exe "C:/Thing.py"
Traceback (most recent call last):
  File "C:/Thing.py", line 30, in <module>
   df = pd.read_sql_query(script,conn)
  File "C:\Python27\lib\site-packages\pandas-0.18.1-py2.7-win32.egg\pandas\io\sql.py", line 431, in read_sql_query
   parse_dates=parse_dates, chunksize=chunksize)
  File "C:\Python27\lib\site-packages\pandas-0.18.1-py2.7-win32.egg\pandas\io\sql.py", line 1608, in read_query
   data = self._fetchall_as_list(cursor)
  File "C:\Python27\lib\site-packages\pandas-0.18.1-py2.7-win32.egg\pandas\io\sql.py", line 1617, in _fetchall_as_list
   result = cur.fetchall()
  File "build\bdist.win32\egg\pypyodbc.py", line 1819, in fetchall
  File "build\bdist.win32\egg\pypyodbc.py", line 1871, in fetchone
ValueError: could not convert string to float: ?

在我看来,在其中一个浮动列中,有一个“?” 出于某种原因的符号。我已联系数据源的所有者,但他们无法更改基础表。

有没有办法使用熊猫替换这样的不正确数据?我试过在read_sql_query声明后使用replace,但我得到了同样的错误。

4

1 回答 1

0

如果没有您的数据,很难确定,但您可以尝试设置coerce_floatFalse,即将您的最后一行替换为

df = pd.read_sql_query(script, conn, coerce_float=False)

请参阅 的文档read_sql_query

于 2016-05-18T18:11:25.027 回答