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

如何在Python中高效合并两个数据集:基于Labels匹配添加动态备注

解决方案

实现步骤

  1. 预处理小数据集生成映射
    遍历数据量较小的NotesData,将其转换为以Labels为键的字典,值为处理好的备注键值对(键名格式为原键名_Note)。后续匹配时可通过标签快速查找,避免重复遍历。

  2. 高效匹配更新大数据集
    单次线性遍历ChartData(数千条数据完全可行),通过每个元素的Labels字段查找预处理好的映射,若存在匹配则将备注信息合并到当前元素中。

代码实现

# 预处理NotesData,构建Labels到备注的映射
notes_map = {}
for note in NotesData:
    current_label = note["Labels"]
    # 生成"键名_Note"格式的备注字典
    note_content = {f"{key}_Note": value for key, value in note.items() if key != "Labels"}
    notes_map[current_label] = note_content

# 更新ChartData
for item in ChartData:
    item_label = item["Labels"]
    if item_label in notes_map:
        # 合并备注信息到当前元素
        item.update(notes_map[item_label])

效果验证

运行上述代码后,ChartData会被更新为:

[
    {
        'ForDate': '2020-12-31T00:00:00',
        'ForYear': 2020,
        'Labels': 'Q1-17',
        'EPCCO': 29.459162790697675,
        'QACCO': 20.10097777777778,
        'EPCCO_Note': 'This is Eppco Note',
        'QACCO_Note': 'This is QACCO Notes'
    }
]

优势说明

  • 高效性:仅两次线性遍历(小数据集一次,大数据集一次),时间复杂度为O(m + n),避免了嵌套循环的O(m*n)低效操作
  • 灵活性:自动适配NotesData中的动态键名,无论除Labels外有多少个不同键,都会按格式生成备注字段
  • 低内存消耗:预处理后的映射字典仅存储必要的备注信息,不会占用过多内存

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:04:53