特征变量含不可打印字符,Pandas DataFrame切片失败如何解决?
问题:DataFrame清理不可打印字符后仍无法按国家名称切片
我从人口普查数据中导入多个CSV文件,纵向合并成DataFrame后,尝试按Label列(国家/地区名称)切片始终失败,推测是CSV中存在不可打印字符导致的。我编写了清理代码但未生效:
import pandas as pd import re # 定义一个用于移除字符串中不可打印字符的函数 def remove_non_printable(text): # 使用正则表达式移除不可打印字符 printable_pattern = re.compile(r'[\x00-\x08\x0E-\x1F\x7F]+') return printable_pattern.sub('', text) # 将函数应用到DataFrame的每个单元格 cleaned_df = df.applymap(remove_non_printable) # 输出清理后的DataFrame print(cleaned_df)
执行后输出(部分):
Year Label Total_Population 0 2010 Total: 38,674,773 1 2010 Europe: 4,847,078 2 2010 Northern Europe: 938,120 3 2010 United Kingdom (inc. Crown Depende... 684,806 4 2010 United Kingdom, excluding Engl... 252,267 .. ... ... ... 486 2021 Venezuela 457,958 487 2021 Other South America 38,509 488 2021 Northern America: 828,196 489 2021 Canada 818,916 490 2021 Other Northern America 9,280 [491 rows x 3 columns]
解决办法
1. 先排查真实字符
先查看Label列字符串的原始表示,确认不可见字符类型:
# 查看前10个Label的原始字符 print(df['Label'].head(10).apply(repr))
这会显示字符串里的所有字符,比如'Canada\xa0'(带非断空格)、'United Kingdom\n'(带换行符)这类肉眼看不到的字符。
2. 优化清理逻辑
之前的正则未覆盖全不可见字符(比如非ASCII空白符、部分控制字符),且无需处理所有列,只针对Label列即可:
import pandas as pd import re def clean_label(text): if not isinstance(text, str): return text # 移除所有不可打印控制字符 text = re.sub(r'[\x00-\x1F\x7F-\x9F]', '', text) # 将所有空白类字符(包括非断空格、制表符等)替换为普通空格,再去首尾空格 text = re.sub(r'\s+', ' ', text).strip() # 处理输出中显示的省略号(如果是CSV中实际存在的) text = text.replace('...', '') return text # 复制原DataFrame并仅清理Label列 cleaned_df = df.copy() cleaned_df['Label'] = cleaned_df['Label'].apply(clean_label) # 测试切片是否生效 print(cleaned_df[cleaned_df['Label'] == 'Canada'])
3. 额外验证
如果还是无法匹配,可尝试标准化字符串(比如统一大小写、移除标点):
cleaned_df['Label'] = cleaned_df['Label'].str.lower().str.replace(r'[^\w\s]', '', regex=True) # 再用小写匹配 print(cleaned_df[cleaned_df['Label'] == 'canada'])
内容的提问来源于stack exchange,提问作者Sean
相关产品推荐
相关产品推荐

