百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

在 Pandas 中使用 Merge、Join 、Concat合并数据的效率对比

liuian 2025-01-12 16:25 13 浏览

在 Pandas 中有很多种方法可以进行DF的合并。本文将研究这些不同的方法,以及如何将它们应用到我们的数据中。

合并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() 函数进一步合并。

# 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’参数指定根据哪列进行合并。

让我们看看下面的例子,我们如何将单索引 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 Joins操作都可以针对指定的列进行合并操作(SQL中的join)那么他们的执行效率是否相同呢?下面我们来进行一下测。

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

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

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

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

相关推荐

vue怎么和后端php配合

Vue和后端PHP可以通过HTTP请求进行配合。首先,前端Vue可以使用axios库或者Vue自带的$http对象来发送HTTP请求到后端PHP接口。通过axios库发送POST、GET、PUT等请求...

Ansible最佳实践之 AWX 使用 Ansible 与 API 通信

#头条创作挑战赛#API简单介绍红帽AWX提供了一个类似Swagger的RESTful风格的Web服务框架,可以和awx直接交互。使管理员和开发人员能够在webUI之外控制其...

PHP8.3 错误处理革命:Exception 与 Error 全面升级

亲爱的小伙伴,好久没有发布信息了,最近学习了一下PHP8.3的升级,都有哪些优化和提升,把学到的分享出来给需要的小伙伴充下电。技术段位:高可用性必修目标收益:精准错误定位+异常链路追踪适配场景...

使用 mix/vega + mix/db 进行现代化的原生 PHP 开发

最近几年在javascript、golang生态中游走,发现很多npm、gomod的优点。最近回过头开发MixPHPV3,发现composer其实一直都是一个非常优秀的工具,但是...

15 个非常好用的 JSON 工具

JSON(JavaScriptObjectNotation)是一种流行的数据交换格式,已经成为许多应用程序中常用的标准。无论您是开发Web应用程序,构建API,还是处理数据,使用JSON工具可以大...

php8环境原生实现rpc

大数据分布式架构盛行时代的程序员面试,常常遇到分布式架构,RPC,本文的主角是RPC,英文名为RemoteProcedureCall,翻译过来为“远程过程调用”。主流的平台中都支持各种远程调用技术...

「PHP编程」如何搭建私有Composer包仓库?

在前一篇文章「PHP编程」如何制作自己的Composer包?中,我们已经介绍了如何制作自己的composer包,以及如何使用composer安装自己制作的composer包。不过,这其中有...

WAF-Bypass之SQL注入绕过思路总结

过WAF(针对云WAF)寻找真实IP(源站)绕过如果流量都没有经过WAF,WAF当然无法拦截攻击请求。当前多数云WAF架构,例如百度云加速、阿里云盾等,通过更改DNS解析,把流量引入WAF集群,流量经...

【推荐】一款 IDEA 必备的 JSON 处理工具插件 — Json Assistant

JsonAssistant是基于IntelliJIDEs的JSON工具插件,让JSON处理变得更轻松!主要功能完全支持JSON5JSON窗口(多选项卡)选项卡更名移动至主编辑器用...

技术分享 | 利用PHAR协议进行PHP反序列化攻击

PHAR(“PhpARchive”)是PHP中的打包文件,相当于Java中的JAR文件,在php5.3或者更高的版本中默认开启。PHAR文件缺省状态是只读的,当我们要创建一个Phar文件需要修改...

php进阶到架构之swoole系列教程(一)windows安装swoole

目录概述安装Cygwin安装swoolephp7进阶到架构师相关阅读概述这是关于php进阶到架构之swoole系列学习课程:第一节:windows安装swoole学习目标:在Windows环境将搭建s...

go 和 php 性能如何进行对比?

PHP性能很差吗?每次讲到PHP和其他语言间的性能对比,似乎都会发现这样一个声音:单纯的性能对比没有意义,主要瓶颈首先是数据库,其次是业务代码等等。好像PHP的性能真的不能单独拿出来讨论似的。但其实一...

Linux(CentOS )手动搭建LNMP(Linux+Nginx+Mysql+PHP)坏境

CentOS搭建LNMP(Linux+Nginx+Mysql+PHP)坏境由于网上各种版本新旧不一,而且Linux版本也不尽相同,所以自己写一遍根据官网的提示自己手动搭建过程。看官方文档很重要,永远...

json和jsonp区别

JSON和JSONP虽然只有一个字母的差别,但其实他们根本不是一回事儿:JSON是一种数据交换格式,而JSONP是一种非官方跨域数据交互协议。一个是描述信息的格式,一个是信息传递的约定方法。一、...

web后端正确的返回JSON

在web开发中,前端和后端发生数据交换传输现在最常见的形式就是异步ajax交互,一般返回给js都是json,如何才是正确的返回呢?前端代码想要获取JSON数据代码如下:$.get('/user-inf...