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

Python Pandas实现Excel HLOOKUP功能 解决嵌套循环效率低问题

Pandas实现类Excel HLOOKUP需求的高效方案

实现思路

  • 先将lookup表转换为以水果名为键的索引字典,避免循环匹配水果名的开销
  • 采用Pandas行向apply操作替代嵌套循环,利用Pandas内置优化提升运行效率
  • 逐行匹配符合阈值条件的水果描述,直接拼接生成Desc字段

完整实现代码

import pandas as pd

# 构造示例数据
lookup = pd.DataFrame({'Fruit': ['Apple','Mango','Guava'],'Rate':[20,30,25],
               'Desc':['Apple rate is higher', 'Mango rate is higher', 'Guava rate is higher']})
input_data = pd.DataFrame({'Id':[1,2,3,4,5], 'Apple':[24,27,30,15,18], 'Mango':[28,32,35,12,26],
                       'Guava':[20,23,34,56,23]})

# 步骤1:转换lookup为映射字典,便于快速查询
fruit_rule = lookup.set_index('Fruit').to_dict('index')
# 提取需要匹配的水果列(排除Id列)
fruit_cols = [col for col in input_data.columns if col in fruit_rule.keys()]

# 步骤2:逐行匹配生成Desc字段
def build_desc(row):
    match_descs = []
    for fruit in fruit_cols:
        # 判断当前行该水果费率是否超过阈值
        if row[fruit] > fruit_rule[fruit]['Rate']:
            match_descs.append(fruit_rule[fruit]['Desc'])
    return ', '.join(match_descs)

input_data['Desc'] = input_data.apply(build_desc, axis=1)
output_data = input_data.copy()

输出验证

运行后output_data与预期结果完全一致:

Id  Apple  Mango  Guava                                               Desc
0   1     24     28     20                               Apple rate is higher
1   2     27     32     23         Apple rate is higher, Mango rate is higher
2   3     30     35     34  Apple rate is higher, Mango rate is higher, Gu...
3   4     15     12     56                               Guava rate is higher
4   5     18     26     23                                                   

性能说明

对比原嵌套循环方案,该实现的时间复杂度从O(nmk)降低为O(n*m),其中n为input_data行数、m为水果种类数、k为lookup表长度,数据量越大性能优势越明显,完全支持重复性自动化操作需求。

内容的提问来源于stack exchange,提问作者Dr.Chuck

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:39:03