1. 程式人生 > 其它 >在 Pandas 中使用 Merge、Join 、Concat合併資料的效率對比

在 Pandas 中使用 Merge、Join 、Concat合併資料的效率對比

在 Pandas 中有很多種方法可以進行DF的合併。本文將研究這些不同的方法,以及如何將它們執行速度的對比。

合併DF

Pandas 使用 .merge() 方法來執行合併。

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

執行我們的程式碼後,有兩個 DataFrame,如下所示。

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

使用 merge() 函式進一步合併。

  1. # using .merge() function
  2. new_data = pd.merge(df1, df2, on='identification')

這產生了下面的新資料;

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

.join() 方法也可以將不同索引的 DataFrame 組合成一個新的 DataFrame。我們可以使用引數‘on’引數指定根據哪列進行合併。

讓我們看看下面的例子,我們如何將單索引 DataFrame 與多索引 DataFrame 連線起來;

完整文章:

https://avoid.overfit.cn/post/e5572b2110ac489fafa226403e70105d