当前位置: 首页 > 编程文章 >

Pandas中Merge、Join与Concat合并数据的效率对比分析

Pandas中Merge、Join与Concat合并数据的效率对比分析

作者:沈川时间:2026-05-12 09:50:57浏览:336

本文对比了Pandas中merge、join和concat三种数据合并方法的执行效率。通过100万至1000万行数据的实验发现,join操作在处理大规模数据时速度显著优于merge,运行时间增长更平缓。对于需要处理大量数据的场景,推荐使用join方法以提升性能。

本文目录收起

在 Pandas 中,有多种方法可用于合并 DataFrame(数据框)。

本文将深入探讨这些不同的方法,并对比它们的执行速度。

合并DF

Pandas 提供了 .merge() 方法来执行合并操作。

import pandas as pd  
# a dictionary to convert to a dataframe
data1 = {'identification': ['a', 'b', 'c', 'd'],
      'Customer_Name':['King', 'West', 'Adams', 'Mercy'],         'Category':['furniture', 'Office Supplies', 'Technology', 'R_materials'],}  
# our second dictionary to convert to a dataframe  
data2 = {'identification': ['a', 'b', 'c', 'd'],
      'Class':['First_Class', 'Second_Class', 'Same_day', 'Standard Class'],  
      'Age':[60, 30, 40, 50]}  
# Convert the dictionary into DataFrame  
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)  

运行代码后,我们得到两个 DataFrame,如下所示。

identification Customer_Name Category 0 a King furniture 1 b West Office Supplies 2 c Adams Technology 3 d Mercy R_materials identification Class Age 0 a First_Class 60 1 b Second_Class 30 2 c Same_day 40 3 d Standard Class 50

使用 merge() 函数进一步合并。

import pandas as pd
df1=...
df2=...
x= pd. merge( df1,df2,
left_on = "df1_col1",
right_on = "df2_col1" )
# using .merge() function  
new_data = pd.merge(df1, df2, on='identification')

这产生了下面的新数据;

identification Customer_Name Category Class Age 0 a King furniture First_Class 60 1 b West Office Supplies Second_Class 30 2 c Adams Technology Same_day 40 3 d Mercy R_materials Standard Class 50

.join() 方法也可以将不同索引的 DataFrame 组合成一个新的 DataFrame。我们可以使用参数‘on’指定根据哪列进行合并。

import pandas as pd
df1 = ...
df2 = ...
df1.set_index ( "df1_col1", inplace = True)
df2.set_index ( "df2_col1", inplace = True)
x=df1.join( df2)

让我们看看下面的例子,如何将单索引 DataFrame 与多索引 DataFrame 连接起来;

import pandas as pd  
# a dictionary to convert to a dataframe
data1 = {
      'Customer_Name':['King', 'West', 'Adams'],  
    'Category':['furniture', 'Office Supplies', 'Technology'],} 7    
# our second dictionary to convert to a dataframe  
data2 = {
      'Class':['First_Class', 'Second_Class', 'Same_day', 'Standard Class'],  
    'Age':[60, 30, 40, 50]}  
# Convert the dictionary into DataFrame  
Ndata = pd.DataFrame(data1, index=pd.Index(['a', 'b', 'c'], name='identification'))
index = pd.MultiIndex.from_tuples([('a', 'x0'), ('b', 'x1'),
                                ('c', 'x2'), ('c', 'x3')],
                                names=['identification', 'x']) 19  
# Convert the dictionary into DataFrame  
Ndata2 = pd.DataFrame(data2, index= index)
print(Ndata, "\n\n", Ndata2)
# joining singly indexed with
# multi indexed
result = Ndata.join(Ndata2, how='inner')

我们的结果如下所示;

Customer_Name Category Class Age identification x 3 a x0 King furniture First_Class 60 b x1 West Office Supplies Second_Class 30 c x2 Adams Technology Same_day 40 x3 Adams Technology Standard Class 50

连接DF

Pandas 中 concat() 方法可以在垂直方向(axis=0)和水平方向(axis=1)上连接 DataFrame。我们还可以一次连接两个以上的 DataFrame 或 Series。

让我们看一个如何在 Pandas 中执行连接的示例;

import pandas as pd  
# a dictionary to convert to a dataframe
data1 = {'identification': ['a', 'b', 'c', 'd'],
      'Customer_Name':['King', 'West', 'Adams', 'Mercy'],  
      'Category':['furniture', 'Office Supplies', 'Technology', 'R_materials'],}  
# our second dictionary to convert to a dataframe  
data2 = {'identification': ['a', 'b', 'c', 'd'],
      'Class':['First_Class', 'Second_Class', 'Same_day', 'Standard Class'],  
      'Age':[60, 30, 40, 50]}  
# Convert the dictionary into DataFrame  
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)  
#perform concatenation here based on horizontal axis
new_data = pd.concat([df1, df2], axis=1)
print(new_data)

这样就获得了新的 DataFrame :

identification Customer_Name Category identification \ 0 a King furniture a 3 1 b West Office Supplies b 4 2 c Adams Technology c 5 3 d Mercy R_materials d Class Age 0 First_Class 60 1 Second_Class 30 2 Same_day 40 3 Standard Class 50

Merge和Join的效率对比

Pandas 中的 Merge 和 Join 操作都可以针对指定的列进行合并(类似 SQL 中的 join),那么它们的执行效率是否相同呢?下面我们来进行测试。

两个 DataFrame 都有相同数量的行和两列,实验中考虑了从 100 万行到 1000 万行的不同大小的 DataFrame,并在每次实验中将行数增加了 100 万。我对固定数量的行重复了十次实验,以消除任何随机性。下面是这十次试验中合并操作的平均运行时间。

上图描绘了操作所花费的时间(以毫秒为单位)。

正如我们从图中看到的,运行时间存在显着差异——最多相差 5 倍。随着 DataFrame 大小的增加,运行时间之间的差异也会增加。两个 JOIN 操作几乎都随着 DataFrame 的大小线性增加。但是,Join 的运行时间增加的速度远低于 Merge。

如果需要处理大量数据,还是请使用 join() 进行操作。

到此这篇关于 Pandas 使用 Merge 与 Join 和 Concat 分别进行合并数据效率对比分析的文章就介绍到这了,更多相关 Pandas 合并数据效率内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

上一篇
pandas中merge()函数的用法解读

pandas中的merge()函数用于根据特定字段连接两个DataFrame,区别于concat按行列拼接的方式。通过on参数指定连接键,若省略则自动匹配同名列;how参数控制拼接逻辑,包括outer并集、right右置、left左置及inner交集四种模式。本文结合代码示例解析各参数行为及结果差异。

下一篇
R语言merge()函数数据合并指南

本文介绍R语言中merge()函数的数据合并机制。该函数支持内连接、左连接、右连接及全外连接四种模式,通过all、all.x和all.y参数控制保留范围。以cold.states和large.states为例,演示如何基于共同列进行匹配,并处理未匹配行的NA填充问题。

相关文章

更多
Python Pandas 数据处理核心功能详解

Pandas基于NumPy构建,提供Series和DataFrame两种核心数据结构以简化表格数据处理。本文详解如何通过loc、iloc及ix进行多维数据筛选,涵盖dropna、fillna等缺失值处理手段,并深入解析concat、append与merge在数据横向纵向合并中的参数差异与应用场景。

2026.08.04 728
pandas中merge()函数的用法解读

pandas中的merge()函数用于根据特定字段连接两个DataFrame,区别于concat按行列拼接的方式。通过on参数指定连接键,若省略则自动匹配同名列;how参数控制拼接逻辑,包括outer并集、right右置、left左置及inner交集四种模式。本文结合代码示例解析各参数行为及结果差异。

2025.05.14 357
MySQL索引创建删除及使用代价

MySQL中InnoDB和MyISAM引擎会自动为主键或唯一列建立索引,其他列需手动指定。索引创建可通过建表时定义、修改表结构添加或删除。虽然索引提升查询效率,但带来显著的空间和时间代价:每增加一个索引即生成一颗B+树,占用大量存储空间;同时增删改操作需维护节点排序,且查询前需计算多索引成本以选择最优执行计划,过多索引会严重拖慢性能。

2026.10.24 990
MongoDB性能优化及监控指南

本文详解MongoDB的性能优化与监控方法。通过建立基础、文档及组合索引提升查询效率,利用explain命令分析执行计划以针对性优化。开启Database Profiler记录慢查询日志,结合mongostat、db.serverStatus等工具实时监控实例状态,确保数据库高性能运行。

2026.04.26 978
PHP考勤系统性能优化:百万级打卡记录查询缓慢的解决方案

百万级打卡记录查询缓慢,核心在于缺少针对时间范围与员工 ID 的联合索引。直接在考勤表上建立 (employee_id, check_time) 复合索引,并将查询条件严格限定在索引覆盖范围内,可将全表扫描转化为索引查找,响应时间从秒级降至毫秒级。

2025.09.05 971
PHP Opcache 开启与配置指南:提升执行效率

本文详细介绍 PHP Opcache(原Optimizer+)的安装与配置方法。通过 Yum 快速安装 rh-php71-php-opcache,解析 opcache.enable、memory_consumption、max_accelerated_files 等核心参数的作用,并演示如何重启服务及验证安装状态,帮助开发者利用共享内存缓存预编译脚本,显著提升 PHP 代码执行效率。

2025.06.17 967

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。