【问题标题】:encoding in strings in dataframe not recognized in Python在 Python 中无法识别的数据帧中的字符串编码
【发布时间】:2021-10-15 04:20:50
【问题描述】:

我有一个数据集包含错误编码方面的脏数据:

示例:

column_header,    other_column
Kol^u00edn,       ...
^u00d8lstykke,    ...
Aalborg S^u00d8,  ...

我使用 pandas 导入数据(read_csv)并将“^”替换为“”,因此这是编写 unicode 的 Pythonic 方式:

df["column_header"].apply(lambda x: str(x).replace("^", "\\"))

打印时返回:

0          Kol\u00edn
1       \u00d8lstykke
2     Aalborg S\u00d8

但我需要的不是 python \u00ed,而是 unicode 字符 í...

如果我手动 print("Kol\u00edn") 我会得到 Kolín,但它在我的数据框中不起作用。

如何将数据框中的字符串转换为包含实际字符而不是 \u... 表示。

非常感谢任何帮助!

编辑: 可能会有所帮助:

print("Kol\u00edn".encode()) # returns b'Kol\xc3\xadn'
print(df["column_header"][0].encode()) # returns b'Kol\\u00edn'

【问题讨论】:

  • 您在加载文件时使用了什么编码,您的iso-8859-1 是吗?
  • 我在加载数据时没有指定任何编码。原始数据集实际上是具有多种编码的多个组合数据集的肮脏混合物。例如。我也有一些包含 html 字符的字符串,例如“&lt”...但我想先清理 \u... 的东西。我在加载数据时尝试了iso和utf-8编码......同样的问题

标签: python pandas encoding


【解决方案1】:

其实我是在[this answer][1]的帮助下自己找到答案的:

import codecs
df["column_header"].apply(lambda x: codecs.unicode_escape_decode(x.replace("^", "\\"))[0])

# 1. replace all ^ by \
# 2. use codecs library which transforms raw string to unicode string
# "Kol\u00edn" --> u"Kol\u00edn" (the u"" is the key for python to recognize it)

也许其他人也有类似的问题,这会有所帮助
[1]:https://stackoverflow.com/a/57660758/9145756

【讨论】:

    猜你喜欢
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 2014-05-08
    • 1970-01-01
    • 2017-12-31
    相关资源
    最近更新 更多