Python CSV预处理脚本出现IndexError: list index out of range问题求助
问题分析
你遇到的IndexError: list index out of range错误,根源在于当slat_tr和flap_tr均为空列表时,len(slat_tr)+len(flap_tr)的结果为0,导致[template]*(len(slat_tr)+len(flap_tr))*2生成空列表。将空列表传入pandas.DataFrame.append()时,内部索引处理逻辑会触发越界错误(尤其是在旧版pandas中,append方法本身已被标记为弃用,稳定性较差)。
修复方案
方案1:添加非零判断,避免空列表传入append
在执行append操作前,先判断重复次数是否大于0,为空时跳过操作:
def get_mech_update(slat_tr, flap_tr, template): # 计算需要重复的次数 repeat_count = (len(slat_tr) + len(flap_tr)) * 2 if repeat_count > 0: template = template.append([template] * repeat_count, ignore_index=True) # 后续其他逻辑...
方案2:使用pd.concat替代弃用的append方法(推荐)
pandas的append方法已在1.4.0版本弃用,官方推荐使用pd.concat实现DataFrame合并,逻辑更清晰且避免潜在bug:
import pandas as pd def get_mech_update(slat_tr, flap_tr, template): repeat_count = (len(slat_tr) + len(flap_tr)) * 2 if repeat_count > 0: # 构造要合并的DataFrame列表:原template + 重复多次的template merge_list = [template] + [template] * repeat_count template = pd.concat(merge_list, ignore_index=True) # 后续其他逻辑...
额外说明
当repeat_count为0(即slat_tr和flap_tr都为空)时,不需要执行任何合并操作,直接保留原template即可,这符合你当前的调用场景需求。
内容的提问来源于stack exchange,提问作者Danish
相关产品推荐
相关产品推荐

