python - 如何替换熊猫数据框列中的重音符号
问题描述
我有一个dataSwiss
包含瑞士自治市信息的数据框。我想用普通字母替换重音字母。
这就是我正在做的事情:
dataSwiss['Municipality'] = dataSwiss['Municipality'].str.encode('utf-8')
dataSwiss['Municipality'] = dataSwiss['Municipality'].str.replace(u"é", "e")
但我收到以下错误:
----> 2 dataSwiss['Municipality'] = dataSwiss['Municipality'].str.replace(u"é", "e")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)
数据看起来像:
dataSwiss.Municipality
0 Zürich
1 Zürich
2 Zürich
3 Zürich
4 Zürich
5 Zürich
6 Zürich
7 Zürich
我找到了解决方案
s = dataSwiss['Municipality']
res = s.str.decode('utf-8')
res = res.str.replace(u"é", "e")
解决方案
这是一种方式。您可以先转换为字节文字,然后再解码为 utf-8。
s = pd.Series(['hello', 'héllo', 'Zürich', 'Zurich'])
res = s.str.normalize('NFKD')\
.str.encode('ascii', errors='ignore')\
.str.decode('utf-8')
print(res)
0 hello
1 hello
2 Zurich
3 Zurich
dtype: object
pd.Series.str.normalize
使用unicodedata
模块。根据文档:
范式 KD (NFKD) 将应用兼容性分解,即将所有兼容性字符替换为其等效字符。
推荐阅读
- python - `setattr` 在 CPython 中因 `AttributeError` 失败?
- java - 如何从 Java 中的 Scanner 清除输入的字符串?
- python - Visual Studio 没有更改为正确的 python 版本
- python - Python比较gz文件的内容
- html - 如何修复与图像和文本对齐的弹性框
- python - 使用 python 3.9 在 Window 上安装 Jupyter-Notebook 时出错
- css - 使用 grid-template 属性防止列基于内容扩展
- android - 如何在主表之后在我预先存在的数据库中添加动态表?
- reactjs - 嵌套路由在 React Router v6 中不起作用
- django - 如果条件django如何发送值以过滤?