【问题标题】:Getting UnicodeDecodeError when transposing DataFrame in iPython在 iPython 中转置 DataFrame 时出现 UnicodeDecodeError
【发布时间】:2015-06-13 16:54:39
【问题描述】:

我正在从http://www.gapminder.org/data/ 导入 excel 表然后我想切换表的列和行。这就是我得到的错误: “UnicodeDecodeError:‘ascii’编解码器无法解码位置 23389 中的字节 0xc3:序数不在范围内 (128)”

我试图用 DataFrame.decode('utf-8') 但它说DataFrame没有这样的属性。

出现该错误是因为 transpose 无法将某些数据转换为 ascii。那正确吗?但是当我的表是纯数字时,为什么我们需要这样做呢?

非常感谢。

有更多关于错误的信息:

---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-190-a252f2a45657> in <module>()
      1 #your code here
      2 countries = countries.transpose()
----> 3 income.transpose()
      4 #income = income.decode('utf-8')
      5 #content = content.decode('utf-8')

/Users/Sergey/anaconda/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/Sergey/anaconda/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/Sergey/anaconda/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/Sergey/anaconda/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/Sergey/anaconda/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/Sergey/anaconda/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):

/Users/Sergey/anaconda/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 

/Users/Sergey/anaconda/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 0xc3 in position 23389: ordinal not in range(128)

在我花了 40 分钟后,问题自行解决了,我不知道如何解决。我唯一做的就是添加了这段代码:

#encoding=utf8 
import sys
reload(sys)  
sys.setdefaultencoding('utf8')

但是当我删除这个和平时,它仍然有效。有人知道为什么吗?谢谢!!!!

【问题讨论】:

    标签: python ipython-notebook utf


    【解决方案1】:

    如果没有更具体的 ipython 会话知识,很难权威地回答,但这里有一些有根据的猜测:

    至于为什么您会收到该错误,即使您的数据都是数字,它很可能来自索引标签之一(可能包含一些文本)。

    至于为什么在删除该代码时它仍然有效,如果您在 iPython notebook 中工作,那么一旦您运行将默认编码设置为 utf-8 的代码,该设置将一直有效,直到任一

    • 运行了一些其他代码来更改设置,或者
    • 你重启了python内核

    【讨论】:

    • 当您说其中一个标签时,您的意思是其中一个数据单元格可能包含文本?这是一个巨大的数据框,我认为我无法手动找到导致错误的单元格。但我很好奇,从字面上看,那个单元格包含的是“234”而不是 234。对吗?
    • 我的意思是我认为它可能是其中一个行或列名称中的非 ascii 字符。
    猜你喜欢
    • 1970-01-01
    • 2022-10-06
    • 2017-01-05
    • 1970-01-01
    • 2014-11-02
    • 2019-06-17
    • 2021-08-19
    • 2014-03-13
    • 2019-01-10
    相关资源
    最近更新 更多