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

如何跳过缺失数据组合,继续执行Pandas循环遍历?

问题描述

需要实现一个逻辑:基于subject和treatment列的条件,提取Expert_Grading_Score列中第一个值为1的实例。操作步骤及问题如下:

  1. 先提取两列的唯一值列表:
subj_list = df_sorted['subj'].unique().tolist()
print(subj_list)

输出:

[1001, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022]
Treatment_list = df_sorted['Treatment'].unique().tolist()
print(Treatment_list)

输出:

['MPPDDu', 'Product A', 'Product C', 'Product D', 'Product E', 'Product F', 'Product G', 'Product H', 'Std S2', 'Product B', 'Product I', 'Product J']
  1. 编写嵌套循环提取数据:
score = 1 
for idx, subject in enumerate(subj_list):
    for idx2, treatment in enumerate(Treatment_list):
        selected_subsite = df_sorted[(df_sorted.subj == subject) & (df_sorted.Treatment == treatment) & (df_sorted.Expert_Grading_Score == score)].iloc[0]
        print(selected_subsite)

运行时处理1001号subject的Product B时触发索引错误,原因是部分subject不存在对应treatment的组合,添加空值判断的continue语句无效,需要调整代码跳过缺失数据点。

解决方案

问题核心是:当筛选后的结果为空DataFrame时,直接调用iloc[0]会抛出索引越界错误。必须先判断筛选后的数据集是否非空,再执行提取操作。

基础修改方案(保留嵌套循环逻辑)

score = 1 
for idx, subject in enumerate(subj_list):
    for idx2, treatment in enumerate(Treatment_list):
        # 先保存筛选结果
        filtered_df = df_sorted[(df_sorted.subj == subject) & 
                                (df_sorted.Treatment == treatment) & 
                                (df_sorted.Expert_Grading_Score == score)]
        # 仅当筛选结果非空时,提取并输出第一行
        if not filtered_df.empty:
            selected_subsite = filtered_df.iloc[0]
            print(selected_subsite)

关键说明

  • 先将筛选结果存入变量,通过filtered_df.empty判断是否有符合条件的数据
  • 空结果会自动跳过当前循环,无需额外写continue
  • 仅在非空时执行iloc[0],彻底避免索引错误

更高效的替代方案(用分组替代嵌套循环)

可以利用Pandas的分组功能,直接获取所有存在的subj-Treatment配对中第一个符合分数条件的行,无需手动遍历空组合:

score = 1
# 先筛选出所有分数为1的数据
score_1_df = df_sorted[df_sorted.Expert_Grading_Score == score]
# 按subject和Treatment分组,取每组第一行
result = score_1_df.groupby(['subj', 'Treatment']).first().reset_index()
# 遍历结果输出
for _, row in result.iterrows():
    print(row)

这种方法自动忽略不存在的subj-Treatment组合,代码更简洁高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:15:19