批量重命名多文件指定索引列遇IndexError问题排查
批量重命名CSV列标题触发IndexError的排查与解决
问题场景
需要为约50个CSV文件重命名列标题:每个文件应包含8列,第1列为行号,其余7列按索引重命名为['Awareness','Brand_Recall','Consideration','Purchase_Intent','Ad_Recall','Product_Use','User_Id']。因原列名存在细微差异,采用索引方式处理,但运行代码时触发以下错误:
Traceback (most recent call last): File "/Users/someone/Python/pandas/studysession/brand_studies/existing_consumer_status/clean_files.py", line 54, in mapping() File "/Users/someone/Python/pandas/studysession/studies/existing_consumer_status/clean_files.py", line 15, in mapping old_names = df.columns[column_indices] ~~~~~~~~~~^^^^^^^^^^^^^^^^ File "/Users/someone/Python/pandas/studysession/lib/python3.11/site-packages/pandas/core/indexes/base.py", line 5380, in __getitem__ result = getitem(key) ^^^^^^^^^^^^ IndexError: index 1 is out of bounds for axis 0 with size 1
原代码:
import pandas as pd import glob import os os.chdir('/Users/someone/Python/pandas/studysession/studies/existing_consumer_status/survey_data/') csv_files = glob.glob('/Users/someone/Python/pandas/studysession/studies/existing_consumer_status/survey_data/*.csv') def mapping (): for csv in csv_files: df = pd.read_csv(csv) column_indices = [1,2,3,4,5,6,7] new_names = ['Awareness','Brand_Recall','Consideration','Purchase_Intent','Ad_Recall','Product_Use','User_Id'] old_names = df.columns[column_indices] final_df = df.rename(columns=dict(zip(old_names, new_names))) out = csv +'_survey_final.csv' final_df.to_csv(out) mapping()
错误原因
错误提示index 1 is out of bounds for axis 0 with size 1说明当前处理的CSV文件只有1列,不符合预期的8列。可能的诱因:
- 部分CSV文件的分隔符不是默认的逗号(比如用分号、制表符),导致
read_csv把整行当成1列 - 部分文件本身损坏、列数缺失
- 文件路径包含非目标CSV(比如空文件、格式错误的文件)
解决方案
1. 直接按索引设置列名(更简洁高效)
不需要通过旧列名映射,直接修改df.columns的指定索引位置,代码更简洁且避免索引越界问题(前提是文件列数正确)。
2. 添加列数校验与异常处理
在处理每个文件前先检查列数,对不符合要求的文件跳过并打印提示,避免程序崩溃。
3. 适配不同分隔符
如果CSV用了非逗号分隔符,手动指定sep参数(比如sep=';'或sep='\t'),或者用sep='\s*,\s*'处理带空格的逗号分隔符。
修改后的代码
import pandas as pd import glob import os # 目标路径 target_dir = '/Users/someone/Python/pandas/studysession/studies/existing_consumer_status/survey_data/' os.chdir(target_dir) csv_files = glob.glob(f'{target_dir}/*.csv') # 定义新列名:第1列保留原名称,后面7列替换为指定名称 new_col_names = ['Awareness','Brand_Recall','Consideration','Purchase_Intent','Ad_Recall','Product_Use','User_Id'] def mapping(): for csv_path in csv_files: try: # 处理可能的分隔符问题,这里假设是逗号,如有其他分隔符可修改sep参数 df = pd.read_csv(csv_path, sep=',') # 校验列数 if len(df.columns) != 8: print(f"跳过文件 {csv_path}:列数异常,当前为{len(df.columns)}列(预期8列)") continue # 直接修改索引1到7的列名 df.columns.values[1:8] = new_col_names # 生成输出路径 out_path = f"{os.path.splitext(csv_path)[0]}_survey_final.csv" # 保存时不要写入默认的索引列(如果原第1列是行号,不需要额外索引) df.to_csv(out_path, index=False) print(f"处理完成:{csv_path}") except Exception as e: print(f"处理文件 {csv_path} 时出错:{str(e)}") mapping()
额外说明
- 如果原第1列不是行号而是无意义的默认索引,读取时可以用
index_col=0参数将其设为索引 - 若不确定分隔符,可尝试
sep='\s+'(匹配任意空白符)或engine='python'提升兼容性
内容的提问来源于stack exchange,提问作者BossHard
相关产品推荐
相关产品推荐

