【问题标题】:python pandas read_cvs load utf-8python pandas read_cvs 加载 utf-8
【发布时间】:2017-08-29 02:45:59
【问题描述】:

我正在尝试read_csv 带有pandas 的西里尔字符的 csv 文件。

import pandas
data = pandas.read_csv('dataset.csv', delimiter='\|\|', engine='python', encoding='utf-8')
print type(data.name[0])

<type 'str'>

在这里,我希望得到unicode

print type(u'hello')

<type 'unicode'>

我做错了什么?

【问题讨论】:

  • Python 是鸭式的。你永远不应该询问对象是什么类型。话虽这么说,您需要提供某种示例,在其中展示您拥有什么以及您想要的输出是什么。您的代码显示正确 AFAIK
  • 我不知道pandas是如何实现read_csv方法的,但是如果它使用了std.lib。 csv 模块,那么解决这个问题可能并不简单,因为 Python 2 的 csv 不支持解码文件(事实上,这很可悲)。现在切换到 Python 3 的另一个理由!

标签: python csv pandas unicode utf-8


【解决方案1】:

简答:Unicode 是未编码文本。 UTF-8 是一种编码 unicode 字符的方式。当 pandas 导入您的 utf-8 编码文本时,它会将其转换为 python str 类型,即解码文本。在 python 3 中,str 类型与 unicode 相同。

如需更深入的了解,请参阅:

  1. UTF-8 vs Unicode
  2. Python str vs Unicode

【讨论】:

  • 非常感谢您的澄清。
  • OP 显然使用的是 Python 2(请参阅打印语句)。在 Python 2 中,decoded(我认为这就是“未编码”的意思)文本的类型为 unicode。因此,显然,pandas 没有正确解码输入文本。
  • 公平点...我不确定这在 python 2 中是如何工作的。有什么想法@lenz?
  • 看着pandas' read_csv documentation,我强烈怀疑他们正在使用std.lib。 csv 模块(因为关键字“quoting”、“quotechar”等)。这意味着它需要 Python 2 中的解决方法,例如解析后解码。
猜你喜欢
  • 1970-01-01
  • 2014-04-18
  • 2015-05-20
  • 2016-01-05
  • 2018-05-17
  • 1970-01-01
  • 2021-02-07
相关资源
最近更新 更多