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

如何向量化实现Pandas单元格函数应用及处理调用失败场景?

向量化改写DataFrame操作及异常处理方案

一、基础向量化实现

针对需求的批量操作,可直接利用pandas的批量处理能力替代itertuples循环,实现高效向量化操作:

import pandas as pd

# 初始化DataFrame
d = {'col1': [1, 2], 'col2': [None, None], 'col3': [None, None]}
df = pd.DataFrame(data=d)

def func(a):
    return a+1, a+5

# 1. 筛选出col1等于1的行的掩码
mask = df['col1'] == 1
# 2. 对目标行的col1批量应用func,将返回的二元组转为DataFrame
result_df = pd.DataFrame(
    df.loc[mask, 'col1'].apply(func).tolist(),
    index=df[mask].index,
    columns=['col2', 'col3']
)
# 3. 将结果批量赋值回原DataFrame
df.loc[mask, ['col2', 'col3']] = result_df

执行后结果与原循环完全一致,但避免了逐行循环的性能开销,内存占用也更低。

二、处理含网络调用的异常场景

当func包含网络调用时,给函数添加异常捕获逻辑,让失败时返回None(会被pandas自动转为NaN),即可实现原循环中continue跳过该行的效果:

import requests  # 示例用requests做网络调用,替换为你的实际网络库

def func_with_error_handle(a):
    try:
        # 替换为你的实际网络调用逻辑
        # resp = requests.get(f"https://your-api.com?param={a}")
        # resp.raise_for_status()  # 触发HTTP错误异常
        # 模拟业务处理,返回结果
        return a+1, a+5
    except requests.exceptions.RequestException as e:
        # 捕获所有网络相关异常,返回None表示失败
        return None, None
    except Exception as e:
        # 可选:捕获其他可能的异常
        return None, None

# 同样的批量处理逻辑
mask = df['col1'] == 1
result_df = pd.DataFrame(
    df.loc[mask, 'col1'].apply(func_with_error_handle).tolist(),
    index=df[mask].index,
    columns=['col2', 'col3']
)
df.loc[mask, ['col2', 'col3']] = result_df

如果网络调用是IO密集型任务,可借助swifter库实现自动并行加速(需提前安装pip install swifter),只需把apply替换为swifter.apply,它会根据数据量自动选择最优并行策略:

import swifter
result_df = pd.DataFrame(
    df.loc[mask, 'col1'].swifter.apply(func_with_error_handle).tolist(),
    index=df[mask].index,
    columns=['col2', 'col3']
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:15:38