我想将csv文件读入熊猫数据框。但是,csv包含重音符号。我正在使用Python 2.7将CSV文件读入Pandas Dataframe中,并显示无效字符(重音符号)
我遇到了UnicodeDecodeError
,因为第一列有重音。我读过一堆网站,如this SO question about UTF-8 in CSV files,this blog post on CSV errors related to newlines和this blog post on UTF-8 issues in Python 2.7。
我用我从那里找到的答案尝试修改我的代码。原来我有:
import pandas as pd
#Create a dataframe with the data we are interested in
df = pd.DataFrame.from_csv('MYDATA.csv')
mode = lambda ts: ts.value_counts(sort=True).index[0]
cols = df['CompanyName'].value_counts().index
df['Calls'] = df.groupby('CompanyName')['CompanyName'].transform(pd.Series.value_counts)
Excetera。它的工作,但现在传递“你”和“东北”作为一个客户的名字是给错误:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xea in position 7: invalid continuation byte
我试图改变行 DF = pd.read_csv(“MYDATA.csv”,编码='utf-8') 但是这给出了同样的错误。
所以我试图从我研究发现的建议,但它也不工作,并且我得到相同的错误。
import pandas as pd
import csv
def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
for row in csv_reader:
yield [unicode(cell, 'utf-8') for cell in row]
reader = unicode_csv_reader(open('MYDATA.csv','rU'), dialect = csv.reader)
#Create a dataframe with the data we are interested in
df =pd.DataFrame(reader)
我觉得将csv数据读入熊猫数据框不应该这么困难。有谁知道更简单的方法?
编辑:什么是真正奇怪的是,如果我用重音字符删除行我仍然得到错误
UnicodeDecodeError: 'utf8' codec can't decode byte 0xd0 in position 960: invalid continuation byte.
这是奇怪,因为我的测试CSV有19行27列。但我希望如果我为整个csv解码utf8,它将解决这个问题。
请不要使用'from_csv'它不再更新使用顶层'read_csv'请试试这个:'df = pd.read_csv(MYDATA.csv',encoding ='utf-8')' – EdChum
是的,我也试过这个,但是我收到错误“AttributeError:type object'DataFrame'没有属性'read_csv'”如果我的行是:df = pd.DataFrame.read_csv('testing2.csv',encoding =' utf-8'),否则如果有两行ra = pd.read_csv('testing2.csv',encoding ='utf-8'),则得到相同的UnicodeDecodeError // df = Dataframe(ra) – jenryb
那么错误是如果你仔细阅读我的代码,它会显示'pd.read_csv'so'import pandas as pd df = pd.read_csv(MYDATA.csv',encoding ='utf- 8')' – EdChum