You need to enable JavaScript to run this app. Pandas遍历数据帧时如何将.iterrows()替换为.itertuples()提升性能
优惠活动
大模型
产品
解决方案
定价
更多

Pandas遍历数据帧时如何将.iterrows()替换为.itertuples()提升性能

Pandas itertuples替换iterrows实现方案

性能差异说明

iterrows遍历每一行时会将行数据转换为Series对象,属性访问、类型转换的开销极高,而itertuples直接返回Python原生命名元组,无额外封装开销,相同逻辑下遍历速度通常能提升5~20倍。

对应业务逻辑的落地代码

针对「当product_name为'sugar'且sold字段值大于0时,将对应行的order字段设为5」的需求,替换后的实现如下,效果和原代码完全一致:

# 默认itertuples(index=True)返回的命名元组会携带行索引,对应属性为Index
for row in df.itertuples():
    # 直接通过命名元组的属性取列值,无需重复调用df.loc做判断
    if row.product_name == 'sugar' and row.sold > 0:
        df.loc[row.Index, "order"] = 5

通用遍历模板替换规则

你原先的通用iterrows模板为:

for index, row in df.iterrows():
    if df.loc[index, "column_name"] == something and df.loc[index, "column_name"] > 0:
         df.loc[index, "column_name"] = something

替换为itertuples的通用写法为:

for row in df.itertuples():
    if row.column_name == something and row.column_name > 0:
        df.loc[row.Index, "column_name"] = something

常见踩坑注意事项

  • 列名若包含空格、特殊符号(如product name、sold$),itertuples会自动将其替换为下划线(如product_name、sold_),此时需以替换后的命名访问属性,或改用row[df.columns.get_loc("原始列名")]的方式取值
  • 若无需保留行索引,可调用itertuples(index=False),此时返回的元组不携带索引属性,遍历速度会进一步提升
  • 若列名与命名元组的内置属性(如Index、count)重名,会触发访问报错,此时可设置itertuples(name=None)返回普通元组,通过列的位置索引取值

额外参考:纯列条件判断的逻辑可直接使用向量化赋值,速度比itertuples再高一个数量级,对应业务逻辑的写法为:

df.loc[(df["product_name"] == "sugar") & (df["sold"] > 0), "order"] = 5

仅当需要逐行执行复杂业务逻辑(如调用外部接口、依赖前序行计算结果)时,才推荐使用itertuples做遍历。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.20 18:54:07