You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas匹配DataFrame时报错IndexError: index 0 is out of bounds如何解决

问题原因

你的报错是因为当exp_df按条件筛选后无匹配行时,返回的结果为空,调用.values[0]访问不存在的第0位元素就会触发索引越界。除此之外原始代码还有两个逻辑错误:

  • 循环中直接对duty_df['Ara']整体赋值,每次循环都会覆盖整列所有值,而非仅修改当前遍历的第t行
  • 两个表的日期字段类型可能不一致:duty_df的Duty Date带时分秒,exp_df的From Date为纯日期,直接匹配会因时间部分不一致导致本应匹配的行也匹配失败

解决方案

方案1:修改循环逻辑(适合小数据量)

先统一日期格式,每次循环先判断匹配结果是否为空,为空则直接跳过:

import pandas as pd

# 统一两个表的日期格式,去除时间部分
exp_df['From Date'] = pd.to_datetime(exp_df['From Date']).dt.date
duty_df['Duty Date'] = pd.to_datetime(duty_df['Duty Date']).dt.date
# 初始化Ara列为空值
duty_df['Ara'] = pd.NA

for t in range(len(duty_df)):
    # 先按条件筛选
    matched = exp_df.loc[
        (exp_df['User Id'] == duty_df['User Id'].iloc[t]) &
        (exp_df['Experience Type'] == 'ARA(Rig)') &
        (exp_df['From Date'] == duty_df['Duty Date'].iloc[t])
    ]['Experience Type']
    # 仅当有匹配结果时赋值
    if not matched.empty:
        duty_df.loc[t, 'Ara'] = matched.iloc[0]

方案2:用pandas merge实现(更高效,推荐)

完全避免循环,利用pandas向量化关联操作,性能远优于循环,代码更简洁:

import pandas as pd

# 统一日期格式
exp_df['From Date'] = pd.to_datetime(exp_df['From Date']).dt.date
duty_df['Duty Date'] = pd.to_datetime(duty_df['Duty Date']).dt.date

# 提取exp_df中符合ARA(Rig)条件的行,重命名列用于关联
ara_mapping = exp_df[exp_df['Experience Type'] == 'ARA(Rig)'].rename(
    columns={'From Date': 'Duty Date', 'Experience Type': 'Ara'}
)[['User Id', 'Duty Date', 'Ara']]

# 左连接到duty_df,无匹配的行Ara列自动填充空值
duty_df = duty_df.merge(ara_mapping, on=['User Id', 'Duty Date'], how='left')

内容的提问来源于stack exchange,提问作者Borg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 16:57:00