如何让Python脚本忽略CSV文件中的$、%等特定字符
解决CSV含特殊符号的Python数据处理与绘图问题
问题背景
我有一份存储汽车贷款数据的CSV文件,列字段包含汽车品牌、型号、总成本、APR。想用Python结合matplotlib.pyplot按品牌绘制饼图(饼块大小由APR和总成本决定),但CSV中的$、%符号导致程序报错,同时现有脚本存在转义序列警告。
报错信息
SyntaxError
SyntaxError: invalid syntax
Toyota, Rav4,"$25,814.73",$315.00,3.24%
^
SyntaxWarning
SyntaxWarning: invalid escape sequence '%'
data[column] = pd.to_numeric(data[column].replace('[%,]', '', regex=True), errors='coerce')
原脚本代码
import pandas as pd import matplotlib.pyplot as plt # Read data file_path = 'input_data.csv' data = pd.read_csv(file_path, encoding='unicode_escape') columns = data.columns for column in columns: if pd.api.types.is_numeric_dtype(data[column]): # Ignore symbols data[column] = pd.to_numeric(data[column].replace('[\%,]', '', regex=True), errors='coerce') # Plot colors = plt.cm.Set3.colors plt.pie(data[column], labels=data.index, autopct='%1.1f%%', colors=colors, startangle=140) plt.title(f'Pie Chart for {column}') plt.show() else: print(f"Skipping non-numeric column: {column}")
解决方案
1. 处理CSV中的特殊符号
CSV里的$、%和千分位逗号会让数据被识别为字符串而非数值类型,可在读取CSV时直接用转换器清理这些符号,避免后续类型转换错误。
2. 修正正则转义警告
正则表达式中的\%是无效转义,%在正则中无需转义,直接用[%$,]即可匹配%、$和逗号。
3. 调整饼图数据逻辑
原脚本误用DataFrame的index作为标签,实际应该用汽车品牌列作为饼图标签;同时需要明确用APR或总成本作为饼块大小的数据源。
修复后的完整脚本
import pandas as pd import matplotlib.pyplot as plt # 定义清理函数处理特殊符号 def clean_currency(value): # 移除$符号和千分位逗号 return float(value.replace('$', '').replace(',', '')) def clean_apr(value): # 移除%符号 return float(value.replace('%', '')) file_path = 'input_data.csv' # 读取CSV并指定列转换器(根据实际列名调整) data = pd.read_csv( file_path, converters={ '总成本': clean_currency, 'APR': clean_apr }, encoding='unicode_escape' ) # 绘制APR饼图 plt.figure(figsize=(8, 8)) colors = plt.cm.Set3.colors plt.pie(data['APR'], labels=data['汽车品牌'], autopct='%1.1f%%', colors=colors, startangle=140) plt.title('各品牌汽车贷款APR占比') plt.show() # 绘制总成本饼图 plt.figure(figsize=(8, 8)) plt.pie(data['总成本'], labels=data['汽车品牌'], autopct='%1.1f%%', colors=colors, startangle=140) plt.title('各品牌汽车贷款总成本占比') plt.show()
关键修复说明
- 读取阶段用转换器函数直接清理符号,从源头避免类型错误
- 简化正则表达式格式,消除转义序列警告
- 用汽车品牌列作为饼图标签,确保图表展示信息准确
- 分开绘制APR和总成本的饼图,满足饼块大小由两个指标决定的需求
内容的提问来源于stack exchange,提问作者SkyeBoniwell
相关产品推荐
相关产品推荐

