You need to enable JavaScript to run this app. Python循环处理数据时遭遇RuntimeError如何跳过并继续后续执行
优惠活动
大模型
产品
解决方案
定价
更多

Python循环处理数据时遭遇RuntimeError如何跳过并继续后续执行

解决方案

示例场景(列表遍历跳过异常元素)

你原有代码的问题在于try/except包裹了整个f(i)调用,函数内部一旦抛出异常就会终止整个函数执行,导致子列表后续元素不再处理。可以通过调整异常捕获的位置解决:

方案1:修改原函数f,将异常捕获放在元素遍历内层

t_ints = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
def f(x):
    for i in x:
        try:
            if i==3:
                continue
            elif i ==6:
                raise RuntimeError('NOP')
            print(f'Processing integer {i}')
        except RuntimeError:
            # 捕获到异常直接跳过当前元素,继续下一个
            continue
    print("Done")
    return

后续调用逻辑不需要修改,运行后即可得到你预期的输出。

方案2:如果不能修改原函数f,可手动拆解遍历逻辑

def safe_process_element(i):
    if i==3:
        return
    elif i ==6:
        raise RuntimeError('NOP')
    print(f'Processing integer {i}')

for sub_list in z:
    for i in sub_list:
        try:
            safe_process_element(i)
        except RuntimeError:
            continue
    print("Done")

真实业务场景(DataFrame ID遍历跳过拟合失败项)

你的需求是跳过单个出错ID、继续处理下一个,直接在单个ID的处理逻辑外层加try/except即可,示例代码如下:

import pandas as pd
import numpy as np
from scipy.optimize import curve_fit

# 你的指数递减曲线函数,这里替换为你实际的实现
def exp_decay(x, a, b, c):
    return a * np.exp(-b * x) + c

df = # 你的原始DataFrame
unique_ids = df['ID'].unique()
result_dict = {}

for id_val in unique_ids:
    try:
        # 筛选当前ID的子DataFrame
        sub_df = df[df['ID'] == id_val].copy()
        # 执行曲线拟合,替换为你实际的入参
        params, _ = curve_fit(exp_decay, sub_df['自变量列名'], sub_df['因变量列名'])
        # 计算拟合结果并存入子DataFrame
        sub_df['拟合结果列名'] = exp_decay(sub_df['自变量列名'], *params)
        # 存入结果字典
        result_dict[id_val] = sub_df
    except RuntimeError:
        # 拟合失败直接跳过当前ID,不做任何处理
        continue

上述代码会自动跳过所有拟合失败的ID,18000个ID的遍历不会因为单个异常终止。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 23:06:00