【问题标题】:UnicodeWarning (equal comparison failed to convert both args) on pandas assignment熊猫分配上的 UnicodeWarning(相等比较无法转换两个 args)
【发布时间】:2016-02-03 14:48:52
【问题描述】:

我正在为 pandas 中的新列分配一个标量值:

df[col] = srs[some_index]

我有一个 warnings.simplefilter("error", UnicodeWarning) 来捕捉原本会是警告的内容(如果我了解正在发生的事情并且愿意忽略它,我可能会关闭它)。

这是我得到的回溯:

  File "/my_virtualenv/lib/python2.7/site-packages/pandas/core/frame.py", line 2299, in __setitem__
    self._set_item(key, value)
  File "/my_virtualenv/lib/python2.7/site-packages/pandas/core/frame.py", line 2367, in _set_item
    NDFrame._set_item(self, key, value)
  File "/my_virtualenv/lib/python2.7/site-packages/pandas/core/generic.py", line 1208, in _set_item
    self._data.set(key, value)
  File "/my_virtualenv/lib/python2.7/site-packages/pandas/core/internals.py", line 3331, in set
    loc = self.items.get_loc(item)
  File "/my_virtualenv/lib/python2.7/site-packages/pandas/core/index.py", line 1759, in get_loc
    return self._engine.get_loc(key)
  File "pandas/index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas/index.c:3979)
  File "pandas/index.pyx", line 152, in pandas.index.IndexEngine.get_loc (pandas/index.c:3782)
  File "pandas/index.pyx", line 178, in pandas.index.IndexEngine._get_loc_duplicates (pandas/index.c:4213)
  File "pandas/index.pyx", line 195, in pandas.index.IndexEngine._maybe_get_bool_indexer (pandas/index.c:4469)
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal

FWIW,df 和 srs 中的数据都来自 Excel 工作表(使用 pandas.read_excel() 获取)。很可能(因为并非所有电子表格都发生这种情况)数据中的某处存在非 ascii、unicode 字符。在没有弄清楚究竟是哪条数据导致它崩溃的情况下,我只想让代码能够适应这种情况。

有什么建议吗?

编辑我尝试过的其他事情:

  • df[unicode(col)] = srs[unicode(some_index)]

稍后编辑我提供的解决方案修复的其他表现形式(产生基本相同的错误):

  • df.ix[df.my_col.astype(unicode).eq(""), "my_col"] = 0.0
  • 在回复Jens 评论 re: type() 和 bytes()(因为输入来自 read_excel(),我相信它使用 xlrd),以下可能表明正在发生的事情:

(显然我需要一个非项目符号列表项行才能正确显示下面的代码示例。)

ipdb> type(df.my_col.astype(unicode).iloc[0])
<type 'unicode'>
ipdb> bytes(df.my_col.astype(unicode).iloc[0])
'50000'

'50000' 显然不是 unicode 对象,它看起来像 u'50000'

如果这确实是问题所在,是否有简单的解决方法,还是取决于 xlrd 的开发人员?

【问题讨论】:

  • df[col] = srs[some_index].values[0] 工作吗?
  • 不,因为 srs 是 pandas.Series,而不是 pandas.DataFrame。因此,srs[some_index] 没有属性“values”。
  • 好的,df[col] = srs[some_index][0] 怎么样?
  • 这将返回任何值的第一个字符(假设它是一个字符串),这不是所需的结果。我想要整个价值。
  • 你能得到type() 和实际的bytes() 这两个值吗?当字符(即字节值)没有映射到正确的 unicode 页面时,我在办公应用程序的数据中看到了类似的问题。

标签: python python-2.7 pandas unicode xlrd


【解决方案1】:

这摆脱了错误,但解决方案感觉不完整,我想更好地理解真正的问题:

df[str(col)] = srs[some_index]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多