【发布时间】:2017-01-17 20:25:48
【问题描述】:
当我使用 pandas.read_csv 读取 CSV 文件时,我得到了这个字符串:
'_\xf4\xd6_'
我无法规范化(删除非 ASCII 字符):
>>> '_\xf4\xd6_'.encode("ascii","ignore")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf4 in position 1: ordinal not in range(128)
我想要的是:
>>> u'_\xf4\xd6_'.encode("ascii","ignore")
'__'
IOW,我需要要么
- 告诉
pandas.read_csv将字符串读取为unicode 或 - 我自己以某种方式将
str转换为unicode。
我该怎么做?
PS。为了完整起见,这里是代码(见Get non-null elements in a pandas DataFrame):
import pandas as pd
def normalize(s):
"Clean-up the string: drop non-ASCII, normalize whitespace."
return re.sub(r"\s+"," ",s,flags=re.UNICODE).encode("ascii","ignore")
df = pd.read_csv("foo.csv",low_memory=False)
my_strings = [normalize(s) for s in df[my_cols].stack.tolist()]
PPS。我无法控制 CSV 文件的内容(即,我无法通过“正确”写入 CSV 文件来解决问题)。
【问题讨论】: