【问题标题】:Unicode encode error while uploading python dataframe上传python数据帧时出现Unicode编码错误
【发布时间】:2016-12-20 17:46:40
【问题描述】:

我有一个读取 csv 或 excel 文件的 python pandas 数据框,如下所示:

if fileType == 'csv':
            df = pd.read_csv( templateFilePath, converters=converters )
        else:
            df = pd.read_excel( templateFilePath, sheetname=sheetName, converters=converters )

        df.fillna( '', inplace=True )

在我尝试上传的文件之一中,它具有值:Banque des Règlements Internationaux (BRI) - Bâle / Bank for International Settlements

因此我不断收到此错误:UnicodeEncodeError: 'ascii' codec can't encode characters in position 12-15: ordinal not in range(128)

我该如何解决这个问题?

更新:

这样做:

        if fileType == 'csv':
            df = pd.read_csv( templateFilePath, converters=converters )
        else:
            df = pd.read_excel( templateFilePath, sheetname=sheetName, converters=converters )

        df.fillna( '', inplace=True )
       # for col in colNames:
        df['COUNTRY_NAME']=df['COUNTRY_NAME'].map(lambda x: x.encode('unicode-escape').decode('utf-8'))

它修复了上传文件时出现的错误。但我不想指定任何列名(就像这里我指定'country_name'),因为 unicode 可以出现在任何列中。我该怎么做?

【问题讨论】:

  • #--coding:utf-8-- 在第一行?

标签: python pandas dataframe


【解决方案1】:

我遇到了UnicodeEncodeError 并使用encoding=latin-1 修复了代码:

if fileType == 'csv':
    try:
        df = pd.read_csv( templateFilePath, converters=converters )
    except UnicodeDecodeError:
        df = pd.read_csv( templateFilePath, converters=converters, encoding='latin-1' )

编辑:

我认为这个问题不再有意义。无论如何,这是对您的其他(看似无关)问题的回答:

def re_encode(x):
    try:
        x_ = x.encode('unicode-escape').decode('utf-8')
    except:
        x_ = x
    return x_

df = df.applymap(re_encode)

【讨论】:

  • 不,它不起作用。起作用的是:df['COUNTRY_NAME']=df['COUNTRY_NAME'].map(lambda x: x.encode('unicode-escape').decode('utf-8')),但我没有想硬编码列名,不能检查所有列吗?
  • 所以这意味着您能够加载数据?
  • 使用:df['COUNTRY_NAME']=df['COUNTRY_NAME'].map(lambda x: x.encode('unicode-escape').decode('utf-8')) 我曾经可以。因为现在 unicode 只存在于“Country_Name”列中,但它也可能存在于其他列中,所以我不想对任何列进行硬编码。
  • 但是进行这样的调用意味着您已经将数据加载到df 对象中。而在尝试创建 df.还是不是这样?
猜你喜欢
  • 1970-01-01
  • 2016-01-25
  • 2011-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 2013-07-25
  • 1970-01-01
相关资源
最近更新 更多