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

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

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

在 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()进行操作。

相关推荐

Python生态下的微服务框架FastAPI

FastAPI是什么FastAPI是一个用于构建API的web框架,使用Python并基于标准的Python类型提示。与flask相比有什么优势高性能:得益于uvloop,可达到与...

SpringBoot:如何解决跨域问题,详细方案和示例代码

跨域问题在前端开发中经常会遇到,特别是在使用SpringBoot框架进行后端开发时。解决跨域问题的方法有很多,我将为你提供一种详细的方案,包含示例代码。首先,让我们了解一下什么是跨域问题。跨域是指在...

使用Nginx轻松搞定跨域问题_使用nginx轻松搞定跨域问题的方法

跨域问题(Cross-OriginResourceSharing,简称CORS)是由浏览器的同源策略引起的。同源策略指的是浏览器限制来自不同源(协议、域名、端口)的JavaScript对资源的...

spring boot过滤器与拦截器的区别

有小伙伴使用springboot开发多年,但是对于过滤器和拦截器的主要区别依然傻傻分不清。今天就对这两个概念做一个全面的盘点。定义与作用范围过滤器(Filter):过滤器是一种可以动态地拦截、处理和...

nginx如何配置跨域_nginx配置跨域访问

要在Nginx中配置跨域,可以使用add_header指令来添加Access-Control-Allow-*头信息,如下所示:location/api{if($reques...

解决跨域问题的8种方法,含网关、Nginx和SpringBoot~

跨域问题是浏览器为了保护用户的信息安全,实施了同源策略(Same-OriginPolicy),即只允许页面请求同源(相同协议、域名和端口)的资源,当JavaScript发起的请求跨越了同源策略,...

图解CORS_图解数学

CORS的全称是Cross-originresourcesharing,中文名称是跨域资源共享,是一种让受限资源能够被其他域名的页面访问的一种机制。下图描述了CORS机制。一、源(Orig...

CORS 幕后实际工作原理_cors的工作原理

跨域资源共享(CORS)是Web浏览器实施的一项重要安全机制,用于保护用户免受潜在恶意脚本的攻击。然而,这也是开发人员(尤其是Web开发新手)感到沮丧的常见原因。小编在此将向大家解释它存在...

群晖无法拉取Docker镜像?最稳定的方法:搭建自己的加速服务!

因为未知的原因,国内的各大DockerHub镜像服务器无法使用,导致在使用群晖时无法拉取镜像构建容器。网上大部分的镜像加速服务都是通过Cloudflare(CF)搭建的,为什么都选它呢?因为...

Sa-Token v1.42.0 发布,新增 API Key、TOTP 验证码等能力

Sa-Token是一款免费、开源的轻量级Java权限认证框架,主要解决:登录认证、权限认证、单点登录、OAuth2.0、微服务网关鉴权等一系列权限相关问题。目前最新版本v1.42.0已...

NGINX常规CORS错误解决方案_nginx配置cors

CORS错误CORS(Cross-OriginResourceSharing,跨源资源共享)是一种机制,它使用额外的HTTP头部来告诉浏览器允许一个网页运行的脚本从不同于它自身来源的服务器上请求资...

Spring Boot跨域问题终极解决方案:3种方案彻底告别CORS错误

引言"接口调不通?前端同事又双叒叕在吼跨域了!""明明Postman能通,浏览器却报OPTIONS403?""生产环境跨域配置突然失效,凌晨3点被夺命连环Ca...

SpringBoot 项目处理跨域的四种技巧

上周帮一家公司优化代码时,顺手把跨域的问题解决了,这篇文章,我们聊聊SpringBoot项目处理跨域的四种技巧。1什么是跨域我们先看下一个典型的网站的地址:同源是指:协议、域名、端口号完全相...

Spring Cloud入门看这一篇就够了_spring cloud使用教程

SpringCloud微服务架构演进单体架构垂直拆分分布式SOA面向服务架构微服务架构服务调用方式:RPC,早期的webservice,现在热门的dubbo,都是RPC的典型代表HTTP,HttpCl...

前端程序员:如何用javascript开发一款在线IDE?

前言3年前在AWSre:Invent大会上AWS宣布推出Cloud9,用于在云端编写、运行和调试代码,它可以直接运行在浏览器中,也就是传说中的WebIDE。3年后的今天随着国内云计算的发...