在 Pandas 中使用 Merge、Join 、Concat合併資料的效率對比
阿新 • • 發佈:2022-05-23
在 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 連線起來;
完整文章:
https://avoid.overfit.cn/post/e5572b2110ac489fafa226403e70105d