使用Pandas apply时触发IndexError索引越界问题求助
Pandas apply返回多值Series触发IndexError的排查思路
问题重现
执行以下代码时触发IndexError: single positional indexer is out-of-bounds:
def make_tonic(title): # 函数逻辑省略 return pd.Series([tonic_chord, Supertonic_chord, Mediant_chord, Subdominant_chord, Dominant_chord, Submediant_chord, Leading_tone_chord, tonics, Supertonic, Mediant, Subdominant, Dominant, Submediant, Leading_tone], index = ['Tonic', 'Supertonic', 'Mediant', 'Subdominant', 'Dominant', 'Submediant', 'Leading Tone', 'Tonic Notes', 'Supertonic Notes', 'Mediant Notes', 'Subdominant Notes', 'Dominant Notes', 'Submediant Notes', 'Leading Tone Notes']) full_scales_2[['Tonic', 'Supertonic', 'Mediant', 'Subdominant', 'Dominant', 'Submediant', 'Leading Tone', 'Tonic Notes', 'Supertonic Notes', 'Mediant Notes', 'Subdominant Notes', 'Dominant Notes', 'Submediant Notes', 'Leading Tone Notes']] = full_scales_2['Scale Notes'].apply(make_tonic)
排查方向
- 返回Series长度与目标列数不匹配:检查
make_tonic返回的列表元素数量是否恰好为14个。若函数内部某个变量未定义、漏写元素,会导致返回Series长度不足,赋值时触发索引越界。 - 函数对部分输入处理异常:取
full_scales_2['Scale Notes']的单条数据传入make_tonic,打印返回结果。若某行输入格式异常(比如非预期的字符串、空值),会导致函数生成的变量不完整,返回的Series长度不符。 - 索引/列名匹配问题:核对目标列名列表与返回Series的index是否完全一致,包括大小写、空格(比如
'Leading Tone'的空格是否和列名完全一致)。索引对齐失败会导致Pandas无法正确映射列,触发索引错误。 - Pandas版本兼容:旧版Pandas在处理
apply返回Series到多列的场景中存在bug,建议升级到Pandas 1.3.x及以上版本重试。
验证步骤
- 单独测试
make_tonic函数:传入样本输入,确认返回Series的长度、索引、元素均正常。 - 检查
make_tonic内部所有变量(tonic_chord至Leading_tone)是否都被正确赋值,无遗漏。 - 逐行对比目标列名和返回Series的index,确保拼写、格式完全一致。
内容的提问来源于stack exchange,提问作者Sir Roland Baggybottom IV
相关产品推荐
相关产品推荐

