使用Pandas时遇列表索引越界,如何正确访问单个索引?
问题:Excel解析Python脚本索引越界错误分析与解决
问题背景
我正在开发一个解析Excel表格数据的Python脚本,目标是通过零件号找到对应行号,再获取该行其他列的单元格值。
当前代码
from pathlib import Path import pandas as pd import re ## OPENING FILES ## # Opens the path to the prints entries = Path(r'C:\Users\jmcintosh\LIDT Project (copy)\LIDT Project\Solidworks Test (DEV)') # Opens Excel sheet for reading xlEntries = pd.read_excel(r'C:\Users\jmcintosh\LIDT Project (copy)\LIDT Project\LIDT New Webspec Titles 2.0.xlsx') ## Variable Definitions ## (Stick to CamelCase "firstLast") partNumbers = [] # Make partNumbers the array for partnumbers, gathers the names as well as the partnumbers specName = [] # Create an array to hold the specification names--this becomes the value of the cells rowNumber = [] # Array for desired row numbers specValue = [] # Array for desired specifications # A 'for' loop that allows iteration through the directory of names. for entry in entries.iterdir(): partNumbertemp = re.findall('[0-9]+', entry.name) partNumbers.append(int(partNumbertemp[0])) # Appends the array with the regex function to parse only the integers of the file name to be used later. # A 'while' loop to remove blank file names from directory issues while ([] in partNumbers): partNumbers.remove([]) fileCount = (len(partNumbers)) # Number of files being edited rowCount = len(xlEntries['StockNumber']) # Number of rows in the Excel document stockNumber = xlEntries['StockNumber'] # Column of stock numbers print(partNumbers[0]) # A 'while' loop to find the row numbers and the the specification name and value of each of the desired row numbers # Reset count for 'while' loop k = 0 while (k<fileCount): rowNumbertemp = xlEntries.loc[xlEntries['StockNumber'] == partNumbers[k]].index.to_numpy() for row in rowNumbertemp: rowNumber.append(int(rowNumbertemp)) specNametemp = xlEntries.loc[rowNumber[k],"Pat's Proposed Change"] for spec in specNametemp: specName.append(specNametemp) specValuetemp = xlEntries.loc[rowNumber[k],"StringValue"] for value in specValuetemp: specValue.append(specValuetemp) k = k + 1 #print(len(rowNumber)) #print(k)
报错信息
Traceback (most recent call last): File "c:\Users\jmcintosh\LIDT PRoject (copy)\LIDT Project\NEW EDMUND OPTICS LIDT\LIDT_MULTIPLE_FILE_TEST.py", line 64, in <module> specNametemp = xlEntries.loc[rowNumber[k],"Pat's Proposed Change"] ~~~~~~~~~^^^ IndexError: list index out of range
rowNumber输出结果
[2382] [2382, 2590] [2382, 2590, 2065] [2382, 2590, 2065, 2383] [2382, 2590, 2065, 2383, 2591] [2382, 2590, 2065, 2383, 2591, 2066] [2382, 2590, 2065, 2383, 2591, 2066, 2379] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381, 2587] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381, 2587, 2588] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381, 2587, 2588, 2589] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381, 2587, 2588, 2589, 2062] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381, 2587, 2588, 2589, 2062, 2063] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381, 2587, 2588, 2589, 2062, 2063, 2064] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381, 2587, 2588, 2589, 2062, 2063, 2064, 2384] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381, 2587, 2588, 2589, 2062, 2063, 2064, 2384, 2385] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381, 2587, 2588, 2589, 2062, 2063, 2064, 2384, 2385, 2592] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381, 2587, 2588, 2589, 2062, 2063, 2064, 2384, 2385, 2592, 2593] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381, 2587, 2588, 2589, 2062, 2063, 2064, 2384, 2385, 2592, 2593, 2067] [2382, 2590, 2065, 2383, 2591, 2066, 2379, 2380, 2381, 2587, 2588, 2589, 2062, 2063, 2064, 2384, 2385, 2592, 2593, 2067, 163]
问题分析
- rowNumber数组添加逻辑错误:代码中
rowNumber.append(int(rowNumbertemp))是将整个numpy数组转成int后添加,而非遍历数组内的单个行号。虽然当前输出显示每个元素是单个数值,但如果某个零件号对应多行数据,这行代码会直接报错;同时冗余的遍历循环会导致重复添加相同值。 - 无匹配行的处理缺失:当某个零件号在Excel中找不到对应StockNumber时,
rowNumbertemp会是空数组,此时for row in rowNumbertemp循环不会执行,rowNumber没有添加任何元素,但k依然递增。当k超过rowNumber的长度时,rowNumber[k]就会触发索引越界错误。 - 冗余代码无效:
while ([] in partNumbers)循环完全无效,因为之前partNumbers.append(int(partNumbertemp[0]))如果partNumbertemp是空数组,会直接触发索引错误,根本不会将空数组添加到partNumbers中。
解决方案
修复后的完整代码
from pathlib import Path import pandas as pd import re ## OPENING FILES ## entries = Path(r'C:\Users\jmcintosh\LIDT Project (copy)\LIDT Project\Solidworks Test (DEV)') xlEntries = pd.read_excel(r'C:\Users\jmcintosh\LIDT Project (copy)\LIDT Project\LIDT New Webspec Titles 2.0.xlsx') ## Variable Definitions ## partNumbers = [] specName = [] rowNumber = [] specValue = [] # 遍历目录提取零件号,增加非空检查 for entry in entries.iterdir(): partNumbertemp = re.findall('[0-9]+', entry.name) if partNumbertemp: # 确保找到数字再添加,避免索引错误 partNumbers.append(int(partNumbertemp[0])) # 批量筛选所有匹配零件号的行,提升效率 matching_rows = xlEntries[xlEntries['StockNumber'].isin(partNumbers)] # 遍历每个零件号获取对应数据 for part_num in partNumbers: # 获取当前零件号对应的行 target_rows = matching_rows[matching_rows['StockNumber'] == part_num] if target_rows.empty: print(f"零件号 {part_num} 未找到匹配行") continue # 遍历匹配到的每一行,收集数据 for idx in target_rows.index: rowNumber.append(int(idx)) specName.append(target_rows.loc[idx, "Pat's Proposed Change"]) specValue.append(target_rows.loc[idx, "StringValue"]) # 验证输出 print("rowNumber:", rowNumber) print("specName:", specName) print("specValue:", specValue)
关键改进点
- 修复行号添加逻辑:直接遍历匹配到的行号索引,逐个添加到rowNumber数组,确保每个元素是单个行号数值。
- 增加无匹配处理:检查当前零件号是否有匹配行,避免空数据导致后续错误。
- 优化代码效率:用pandas的
isin和布尔索引批量筛选数据,替代循环逐个查找,提升运行速度。 - 移除冗余代码:删除无效的
while ([] in partNumbers)循环,增加零件号提取时的非空检查,避免潜在错误。
内容的提问来源于stack exchange,提问作者Jaiven McIntosh
相关产品推荐
相关产品推荐

