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

优化大型DataFrame:用.loc替代iterrows()实现数据匹配更新

高效优化DataFrame匹配替换方案

用iterrows()逐行处理大型DataFrame时效率极低——这种循环完全没利用pandas的向量化运算优势。下面是针对你需求的优化实现,性能能提升几个数量级:

核心思路

  1. 先从df1里筛选出day_of_week == 7的行,只保留匹配需要的statWeek、statMonth和cost_eu列,避免冗余数据干扰。
  2. 用pandas内置的merge做左连接,把df2和筛选后的df1按statWeek+statMonth这两个键匹配,自动把对应行的cost_eu带到df2中。
  3. 用combine_first方法完成替换:有匹配到cost_eu的行就用它替换as_cost_perf,没匹配到的保留原值。

优化后代码

import pandas as pd

# 创建示例数据
data1 = {'day_of_week': [7, 7, 6],
         'statWeek': [1, 2, 3],
         'statMonth': [1, 1, 1],
         'cost_eu': [957940.0, 942553.0, 1177088.0]}
df1 = pd.DataFrame(data1)

data2 = {'statWeek': [1, 2, 3, 4, 1, 2, 3],
         'statMonth': [1, 1, 1, 1, 2, 2, 2],
         'as_cost_perf': [344560.0, 334580.0, 334523.0, 556760.0, 124660.0, 124660.0, 763660.0]}
df2 = pd.DataFrame(data2)

# 1. 筛选df1中符合条件的行,只保留必要列
df1_matching = df1[df1['day_of_week'] == 7][['statWeek', 'statMonth', 'cost_eu']]

# 2. 左连接df2和筛选后的df1,获取匹配的cost_eu
merged_df = df2.merge(df1_matching, on=['statWeek', 'statMonth'], how='left')

# 3. 完成替换:有匹配值用cost_eu,无匹配则保留原as_cost_perf
df2['as_cost_perf'] = merged_df['cost_eu'].combine_first(merged_df['as_cost_perf'])

# 输出结果
print(df2)

为什么更快?

merge是pandas底层用C实现的向量化操作,能一次性处理所有匹配逻辑,完全避免了Python层面的逐行循环开销。对于十万甚至百万级别的数据集,这种方法的运行时间会从分钟级压缩到秒级。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:15:04