【问题标题】:pandas .replace not working in Python 2.7pandas .replace 在 Python 2.7 中不起作用
【发布时间】:2021-08-09 20:05:39
【问题描述】:

我很难理解 pandas 中的 .replace 中的特殊字符。

我有一个数据框,我需要为希腊字母更改一些文本。我以前在相同的代码上做过,而且效果很好,但由于某种原因,我无法弄清楚第二次它不起作用。

import pandas as pd

df = pd.DataFrame({'a' = [Aa_alpha_bb, Cc_beta_dd, Ee_gamma_ff]})

#then I did:
df['a'].replace({'_alpha_':'α', '_beta_':'β', '_gamma_':'γ'}, regex = True, inplace = True)

但我收到以下错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 0: ordinal not in range(128)

我也尝试过使用df['a'].astype(str),但无济于事

我没有在 python 中使用特殊字符和编码的经验。 我也是使用 python 2.7 的新手,因为我现在正在处理的项目需要这个特定版本。 有人可以帮我吗?

【问题讨论】:

  • 尝试做第一行# -*- coding: UTF-8 -*-
  • 我无法重现这个 - 你在什么样的环境中?如果*nix,环境变量'LC_ALL','LC_CTYPE','LANG','LANGUAGE'的值是多少?还是你在 WINDOWS 上?
  • @MDR 如果问题是缺少编码 cookie,则会出现 SyntaxError,而不是 UnicodeDecodeError

标签: python pandas character-encoding special-characters


【解决方案1】:

我很确定这与您的文件不是 utf-8 编码有关。查看其他 stackoverflow 问题:UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

输入第一行等于:

# coding: utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

应该可以解决问题。在 python 3 中,默认设置为 utf8

【讨论】:

  • 不要这样做,这是黑客行为。设置PYTHONIOENCODING 环境变量。
猜你喜欢
  • 1970-01-01
  • 2016-08-20
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 2016-06-19
  • 2011-08-06
相关资源
最近更新 更多