使用Pandas读取CSV指定列时遇Usecols匹配错误求助
Pandas读取CSV指定列报错及解决方案
问题场景
使用Pandas的read_csv方法,通过usecols参数传入包含146个列名的列表读取CSV特定列时,触发报错:
Usecols do not match columns, columns expected but not found
提示有16个列未找到。尝试相关方案无效,测试了四种方法仍未解决:
测试的四种方法
- 方法一:
file1DF=pd.read_csv(pathoffile[0],usecols=file1column) print(file1DF)
- 方法二:
file1DF=pd.read_csv(pathoffile[0],usecols=file1column,sep=',').columns.tolist() print(file1DF)
- 方法三:
e1=pd.read_csv(pathoffile[0],sep=',') e2=pd.DataFrame(exam1) e3=e2[listofcolumns]
- 方法四:
e1=pd.read_csv(pathoffile[0],sep=',') e2=pd.DataFrame(exam1) e3=e2[listofcolumns] jstrlist=Json.dumps(listofcolumns) e3=e2[jstrlist]
方法四触发KeyError,报错信息中146个列名被包裹在双引号的字符串列表"["146 column names"]"中。
核心问题排查与解决
1. 确认列名匹配性
CSV列名常因**空格、大小写、特殊字符(全角/半角、下划线/短横线混淆)**导致匹配失败,先排查差异:
# 读取CSV实际列名 actual_cols = pd.read_csv(pathoffile[0], nrows=0).columns.tolist() # 找出目标列中不存在的列 target_cols = file1column missing_cols = set(target_cols) - set(actual_cols) print("未找到的列:", missing_cols)
2. 统一列名格式
如果发现格式问题,统一清洗后再匹配:
# 清洗实际列名:去首尾空格、转小写 actual_cols_clean = [col.strip().lower() for col in actual_cols] # 同步清洗目标列列表 target_cols_clean = [col.strip().lower() for col in target_cols] # 筛选出匹配的原始列名 matched_cols = [actual_cols[i] for i in range(len(actual_cols)) if actual_cols_clean[i] in target_cols_clean] # 读取数据 df = pd.read_csv(pathoffile[0], usecols=matched_cols)
3. 修复测试方法的错误
- 方法三:变量名写错,
exam1应为e1,且无需重复转DataFrame:
e1 = pd.read_csv(pathoffile[0], sep=',') e3 = e1[listofcolumns]
- 方法四:
Json.dumps会把列表转成字符串,而DataFrame索引需要列名列表,直接用listofcolumns即可,无需转JSON字符串。
4. 特殊场景处理
若CSV列名含隐藏空格或特殊格式,尝试以下参数:
# 忽略列名后的空格 df = pd.read_csv(pathoffile[0], usecols=target_cols, skipinitialspace=True) # 用python引擎提升兼容性 df = pd.read_csv(pathoffile[0], usecols=target_cols, engine='python')
内容的提问来源于stack exchange,提问作者Nija Shree
相关产品推荐
相关产品推荐

