在 Pandas 中使用 Merge、Join 、Concat合并数据的效率对比
在 Pandas 中有很多种方法可以进行DF的合并。本文将研究这些不同的方法,以及如何将它们执行速度的对比。
合并DF
Pandas 使用 .merge() 方法来执行合并。
import pandas as pd# a dictionary to convert to a dataframedata1 = {'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 dataframedata2 = {'identification': ['a', 'b', 'c', 'd'],'Class':['First_Class', 'Second_Class', 'Same_day', 'Standard Class'],'Age':[60, 30, 40, 50]}# Convert the dictionary into DataFramedf1 = pd.DataFrame(data1)df2 = pd.DataFrame(data2)
运行我们的代码后,有两个 DataFrame,如下所示。
identification Customer_Name Category0 a King furniture1 b West Office Supplies2 c Adams Technology3 d Mercy R_materialsidentification Class Age0 a First_Class 601 b Second_Class 302 c Same_day 403 d Standard Class 50
使用 merge() 函数进一步合并。

# using .merge() functionnew_data = pd.merge(df1, df2, on='identification')
这产生了下面的新数据;
identification Customer_Name Category Class Age0 a King furniture First_Class 601 b West Office Supplies Second_Class 302 c Adams Technology Same_day 403 d Mercy R_materials Standard Class 50
.join() 方法也可以将不同索引的 DataFrame 组合成一个新的 DataFrame。我们可以使用参数‘on’参数指定根据哪列进行合并。

让我们看看下面的例子,我们如何将单索引 DataFrame 与多索引 DataFrame 连接起来;
完整文章:
https://avoid.overfit.cn/post/e5572b2110ac489fafa226403e70105d

浙公网安备 33010602011771号