将文本导入 Pandas Dataframe 时出现 Unicode/Ascii 错误

Unicode / Ascii errors importing text into Pandas Dataframe

我正在使用 Python (2.7) 和从 Facebook API 获取数据的请求,然后使用 Pandas 通过 IPython 报告输出。在旅途中的某个地方,我遇到了 Unicode/Ascii 错误,我对要更改的内容感到困惑。

希望解决方案对于精通该领域的人来说是显而易见的。


首先,我使用 Requests 通过我创建的辅助模块获取 API 数据。

_current_request = https://graph.facebook.com/officialWhosebug/feed?access_token=[Redacted access token]
response = requests.get(_current_request)

Requests.json() 由于编码而立即失败,所以我一直在使用以下内容:

encoded = response.content.encode("utf-8")  # Excuse verbosity, just trying
json_response = json.loads(encoded)         # to be clear on my thought
response_list = list()                      # process, and hoping it will help
response_list += json_response["data"]      # debugging.

"data" 键是来自 FB API 的实际内容。它是单个 post 对象的列表)

然后我将 response_list 对象传回 IPython 笔记本进行操作。

[1] pd.DataFrame(response_list)

回溯:

---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-290-0613adf928ec> in <module>()

/Users/Shared/Sites/Virtualenv/api_manager/lib/python2.7/site-packages/IPython/core/displayhook.pyc in __call__(self, result)
    236                 self.write_format_data(format_dict, md_dict)
    237                 self.log_output(format_dict)
--> 238             self.finish_displayhook()
    239 
    240     def cull_cache(self):

/Users/Shared/Sites/Virtualenv/api_manager/lib/python2.7/site-packages/IPython/kernel/zmq/displayhook.pyc in finish_displayhook(self)
     70         sys.stderr.flush()
     71         if self.msg['content']['data']:
---> 72             self.session.send(self.pub_socket, self.msg, ident=self.topic)
     73         self.msg = None
     74 

/Users/Shared/Sites/Virtualenv/api_manager/lib/python2.7/site-packages/IPython/kernel/zmq/session.pyc in send(self, stream, msg_or_type, content, parent, ident, buffers, track, header, metadata)
    647         if self.adapt_version:
    648             msg = adapt(msg, self.adapt_version)
--> 649         to_send = self.serialize(msg, ident)
    650         to_send.extend(buffers)
    651         longest = max([ len(s) for s in to_send ])

/Users/Shared/Sites/Virtualenv/api_manager/lib/python2.7/site-packages/IPython/kernel/zmq/session.pyc in serialize(self, msg, ident)
    551             content = self.none
    552         elif isinstance(content, dict):
--> 553             content = self.pack(content)
    554         elif isinstance(content, bytes):
    555             # content is already packed, as in a relayed message

/Users/Shared/Sites/Virtualenv/api_manager/lib/python2.7/site-packages/IPython/kernel/zmq/session.pyc in <lambda>(obj)
     83 # disallow nan, because it's not actually valid JSON
     84 json_packer = lambda obj: jsonapi.dumps(obj, default=date_default,
---> 85     ensure_ascii=False, allow_nan=False,
     86 )
     87 json_unpacker = lambda s: jsonapi.loads(s)

/Users/Shared/Sites/Virtualenv/api_manager/lib/python2.7/site-packages/zmq/utils/jsonapi.pyc in dumps(o, **kwargs)
     38         kwargs['separators'] = (',', ':')
     39 
---> 40     s = jsonmod.dumps(o, **kwargs)
     41 
     42     if isinstance(s, unicode):

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.pyc in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, encoding, default, sort_keys, **kw)
    248         check_circular=check_circular, allow_nan=allow_nan, indent=indent,
    249         separators=separators, encoding=encoding, default=default,
--> 250         sort_keys=sort_keys, **kw).encode(obj)
    251 
    252 

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.pyc in encode(self, o)
    208         if not isinstance(chunks, (list, tuple)):
    209             chunks = list(chunks)
--> 210         return ''.join(chunks)
    211 
    212     def iterencode(self, o, _one_shot=False):

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 17915: ordinal not in range(128)

显然这是将 Unicode 对象编码/解码到 DataFrame 的过程中的一个问题,但让我感到困惑的是 Pandas 有一个本机 Unicode 对象,所以我不确定为什么要进行 Ascii 转换无论如何都在发生。

在此先感谢您的帮助,请询问我是否需要添加更多信息。


附加信息

我查看了每个字典键的数据类型并确认它是子字典和 Unicode 对象的混合:

Key: picture, <type 'unicode'>
Key: story, <type 'unicode'>
Key: likes, <type 'dict'>
Key: from, <type 'dict'>
Key: comments, <type 'dict'>
Key: message_tags, <type 'dict'>
Key: privacy, <type 'dict'>
Key: actions, <type 'list'>
Key: updated_time, <type 'unicode'>
Key: to, <type 'dict'>
Key: link, <type 'unicode'>
Key: object_id, <type 'unicode'>
Key: story_tags, <type 'dict'>
Key: created_time, <type 'unicode'>
Key: message, <type 'unicode'>
Key: type, <type 'unicode'>
Key: id, <type 'unicode'>
Key: status_type, <type 'unicode'>
Key: icon, <type 'unicode'>

我已经尝试将它们中的每一个重新编码为 str,但这也无济于事 - 而且似乎也没有必要,因为 Pandas 无论如何都可以处理 Unicode .

我在使用 unicode 对象和 pandas 时遇到过类似的问题。需要考虑的几件事:

  1. 在我的例子中,它有助于在尝试从中制作数据框之前查看原始数据,并使用 IPython notebook 以外的编辑器(例如,尝试 vim -b Rawfile.txt 以查找字节顺序标记、幻数等)。 .ipynb 显示可以让事情变得比您实际想要的更漂亮,这意味着它只是为了显示目的而在引擎盖下做一些事情。有些对象可能与它们看起来不同。

  2. 为我修复的是先将我的对象传递到编解码器,然后将其保存到文件,然后再将其转换为数据帧。也许尝试使用您的一部分数据。这也使得尝试不同的编码变得容易。


import codecs

opened = codecs.open(myObject, 'rU', 'UTF16')

df = pandas.DataFrame(opened, index = 'ColName')

  1. 正如您可能已经知道的那样,有时 pandas 会在缺少值时抱怨并且无法弄清楚如何将所有对象强制转换为对称的 形状,例如如果层次索引嵌套不匹配,因为您不允许 NaN。

    确保 unicode 对象的长度与字典的长度相匹配。

    尝试传递列名以与 unicode 对象一起使用(我猜它可能没有键,dict 应有的方式),并确保它知道要用于索引的列。

重新发布作为回答:

这是一个 known issue in at least IPython 3.0, and probably older versions. A fix 已经合并,将在 IPython 3.1.

该问题仅影响 Python 2.