我正在使用带有Python 2.7的Mac和PyoDBC从Microsoft SQL Server查询数据。我的dataFrame
中有一个时间戳列,显示为DateTime64 [ns]程序的结构 -
SQLCommand = (" SELECT Col1, Col2, Col3 from xyztable ")
DF = pd.read_sql(SQLCommand,cnxn)
# extracting Day and month by converting to dt
DF['TS']=DF['TS'].dt.strftime('%d%m%')
# Create labels from Categories (string type data column in SQL table), replacing each category
DF['Flag']= DF['CODE']
DF.dtypes
TS datetime64[ns]
TIWOR object
CODES object
T-enc int8
TS object
TS_HHMM object
TS_DD int64
TS_DDMM int64
Flag object
dtype: object
# I am able to replace all categories but it fails at this step as u2013 appears in the middle of string
DF['Flag'].unique()
array([0, 1, nan, u'Dev u2013 Env'], dtype=object)
# All attempts to find and replace are not working, some records have 'nan' values and DF.dropna does not work.
尝试修复
- 已经提到了各种堆栈溢出文章,但没有帮助。
- 将SQL查询输出导出到CSV文件中并加载到数据框架中,但仍然相同。
DF.to_csv('~/SQLoutput.csv', sep='t', encoding='utf-8')
- 将SQL查询输出导出到Excel文件中并加载到DataFrame中,仍然相同的问题
DF=pd.read_excel('/Users/User1/SQLoutput.xlsx',sheet_name=0,encoding='utf-8')
- 在代码开始时添加了
# -*- coding:utf-8 -*-
,没有帮助 - 已验证的PYODBC设置,没问题。
tsql -S sqlservername -U Username -P Password
在熊猫中未尝试过,但是您也许可以使用unicode
问题(这只是一个记录的示例,请尝试在整列中应用相同):
import unidecode
record = unidecode.unidecode_expect_nonascii(record)