我需要替换 python 2.7 中 pandas 数据框列中的非 ASCII 字符
I need to replace non-ASCII characters in pandas data frame column in python 2.7
这个问题被问过很多次,但没有一个解决方案适合我。
数据框是从第三方 excel 文件中提取的 'UTF-8' 编码:
pd.read_excel(file, encoding = 'UTF-8', sheet_name = worksheet)
但我在某些行中仍然有像“’”这样的字符,而不是“’”。
在代码的顶部我有以下内容
# -*- encoding: utf-8 -*-
以下行不会引发错误,但不会更改数据中的任何内容:
df['text'] = df['text'].str.replace("’","'")
我试过字典(核心相同),比如
repl_dict = {"’": "'"}
for k,v in repl_dict.items():
df.loc[df.text.str.contains(k), 'text'] =
df.text.str.replace(pat=k,repl=v)
并尝试了许多其他方法,包括正则表达式,但没有任何效果。
当我尝试时:
def replace_apostrophy(text):
return text.replace("’","'")
df['text'] = df['text'].apply(lambda x: replace_apostrophy(x))
我收到以下错误 -
UnicodeDecodeError:'ascii' 编解码器无法解码位置 0 中的字节 0xc3:序号不在范围内(128)
当我尝试时:
df["text"] = df["text"].apply(lambda text: unicodedata.normalize('NFKD', text))
我收到以下错误 -
TypeError: normalize() 参数 2 必须是 unicode,而不是 float
文中还有后记的表情符号,我需要数一数。
有人可以给我一个好的建议吗?
非常感谢!
我自己找到了解决办法。它可能看起来很笨拙,但在我的情况下效果很好:
df["text"] = df["text"].apply(lambda text: unicodedata.normalize('NFKD', text).encode('ascii','backslashreplace'))
我必须在 运行 该代码之前替换 nan 值。
该操作只给我可以轻松替换的 ascii 符号:
def replace_apostrophy(text):
return text.replace("a\u0302\u20acTM","'")
希望这对某人有所帮助。
这个问题被问过很多次,但没有一个解决方案适合我。
数据框是从第三方 excel 文件中提取的 'UTF-8' 编码:
pd.read_excel(file, encoding = 'UTF-8', sheet_name = worksheet)
但我在某些行中仍然有像“’”这样的字符,而不是“’”。
在代码的顶部我有以下内容
# -*- encoding: utf-8 -*-
以下行不会引发错误,但不会更改数据中的任何内容:
df['text'] = df['text'].str.replace("’","'")
我试过字典(核心相同),比如
repl_dict = {"’": "'"}
for k,v in repl_dict.items():
df.loc[df.text.str.contains(k), 'text'] =
df.text.str.replace(pat=k,repl=v)
并尝试了许多其他方法,包括正则表达式,但没有任何效果。
当我尝试时:
def replace_apostrophy(text):
return text.replace("’","'")
df['text'] = df['text'].apply(lambda x: replace_apostrophy(x))
我收到以下错误 - UnicodeDecodeError:'ascii' 编解码器无法解码位置 0 中的字节 0xc3:序号不在范围内(128)
当我尝试时:
df["text"] = df["text"].apply(lambda text: unicodedata.normalize('NFKD', text))
我收到以下错误 - TypeError: normalize() 参数 2 必须是 unicode,而不是 float
文中还有后记的表情符号,我需要数一数。
有人可以给我一个好的建议吗?
非常感谢!
我自己找到了解决办法。它可能看起来很笨拙,但在我的情况下效果很好:
df["text"] = df["text"].apply(lambda text: unicodedata.normalize('NFKD', text).encode('ascii','backslashreplace'))
我必须在 运行 该代码之前替换 nan 值。
该操作只给我可以轻松替换的 ascii 符号:
def replace_apostrophy(text):
return text.replace("a\u0302\u20acTM","'")
希望这对某人有所帮助。