本篇详细说明merge的应用,join 和concatenate的拼接方法的与之相似。

  1. pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None,
  2. left_index=False, right_index=False, sort=True,
  3. suffixes=('_x', '_y'), copy=True, indicator=False,
  4. validate=None)

参数如下:

  • left: 拼接的左侧DataFrame对象
  • right: 拼接的右侧DataFrame对象
  • on: 要加入的列或索引级别名称。 必须在左侧和右侧DataFrame对象中找到。 如果未传递且left_index和right_index为False,则DataFrame中的列的交集将被推断为连接键。
  • left_on:左侧DataFrame中的列或索引级别用作键。 可以是列名,索引级名称,也可以是长度等于DataFrame长度的数组。
  • right_on: 左侧DataFrame中的列或索引级别用作键。 可以是列名,索引级名称,也可以是长度等于DataFrame长度的数组。
  • left_index: 如果为True,则使用左侧DataFrame中的索引(行标签)作为其连接键。 对于具有MultiIndex(分层)的DataFrame,级别数必须与右侧DataFrame中的连接键数相匹配。
  • right_index: 与left_index功能相似。
  • how: One of ‘left’, ‘right’, ‘outer’, ‘inner’. 默认inner。inner是取交集,outer取并集。比如left:[‘A’,‘B’,‘C’];right[’’A,‘C’,‘D’];inner取交集的话,left中出现的A会和right中出现的买一个A进行匹配拼接,如果没有是B,在right中没有匹配到,则会丢失。’outer’取并集,出现的A会进行一一匹配,没有同时出现的会将缺失的部分添加缺失值。
  • sort: 按字典顺序通过连接键对结果DataFrame进行排序。 默认为True,设置为False将在很多情况下显着提高性能。
  • suffixes: 用于重叠列的字符串后缀元组。 默认为(‘x’,’ y’)。
  • copy: 始终从传递的DataFrame对象复制数据(默认为True),即使不需要重建索引也是如此。
  • indicator:将一列添加到名为_merge的输出DataFrame,其中包含有关每行源的信息。 _merge是分类类型,并且对于其合并键仅出现在“左”DataFrame中的观察值,取得值为left_only,对于其合并键仅出现在“右”DataFrame中的观察值为right_only,并且如果在两者中都找到观察点的合并键,则为left_only。

1、基础实例:

  1. import pandas as pd
  2. left = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
  3. 'A': ['A0', 'A1', 'A2', 'A3'],
  4. 'B': ['B0', 'B1', 'B2', 'B3']})
  5. right = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
  6. 'C': ['C0', 'C1', 'C2', 'C3'],
  7. 'D': ['D0', 'D1', 'D2', 'D3']})
  8. result = pd.merge(left, right, on='key')
  9. # on参数传递的key作为连接键
  10. result
  11. Out[4]:
  12. A B key C D
  13. 0 A0 B0 K0 C0 D0
  14. 1 A1 B1 K1 C1 D1
  15. 2 A2 B2 K2 C2 D2
  16. 3 A3 B3 K3 C3 D3

2、传入的on的参数是列表:
3、Merge method
如果组合键没有出现在左表或右表中,则连接表中的值将为NA。

Merge method SQL Join Name Description
left LEFTOUTER JOIN Use keys from left frame only
right RIGHT OUTER JOIN Use keys from right frame only
outer FULL OUTER JOIN Use union of keys from both frames
inner INNER JOIN Use intersection of keys from both frames
  1. result = pd.merge(left, right, how='left', on=['key1', 'key2'])
  2. # Use keys from left frame only
  3. result
  4. Out[34]:
  5. A B key1 key2 C D
  6. 0 A0 B0 K0 K0 C0 D0
  7. 1 A1 B1 K0 K1 NaN NaN
  8. 2 A2 B2 K1 K0 C1 D1
  9. 3 A2 B2 K1 K0 C2 D2
  10. 4 A3 B3 K2 K1 NaN NaN
  11. result = pd.merge(left, right, how='right', on=['key1', 'key2'])
  12. # Use keys from right frame only
  13. result
  14. Out[36]:
  15. A B key1 key2 C D
  16. 0 A0 B0 K0 K0 C0 D0
  17. 1 A2 B2 K1 K0 C1 D1
  18. 2 A2 B2 K1 K0 C2 D2
  19. 3 NaN NaN K2 K0 C3 D3
  20. result = pd.merge(left, right, how='outer', on=['key1', 'key2'])
  21. # Use intersection of keys from both frames
  22. result
  23. Out[38]:
  24. A B key1 key2 C D
  25. 0 A0 B0 K0 K0 C0 D0
  26. 1 A1 B1 K0 K1 NaN NaN
  27. 2 A2 B2 K1 K0 C1 D1
  28. 3 A2 B2 K1 K0 C2 D2
  29. 4 A3 B3 K2 K1 NaN NaN
  30. 5 NaN NaN K2 K0 C3 D3
  31. -----------------------------------------------------
  32. left = pd.DataFrame({'A' : [1,2], 'B' : [2, 2]})
  33. right = pd.DataFrame({'A' : [4,5,6], 'B': [2,2,2]})
  34. result = pd.merge(left, right, on='B', how='outer')
  35. result
  36. Out[40]:
  37. A_x B A_y
  38. 0 1 2 4
  39. 1 1 2 5
  40. 2 1 2 6
  41. 3 2 2 4
  42. 4 2 2 5
  43. 5 2 2 6

4、传入indicator参数
merge接受参数指示符。 如果为True,则将名为_merge的Categorical类型列添加到具有值的输出对象:

Observation Origin _merge value
Merge key only in ‘left’ frame left_only
Merge key only in ‘right’ frame right_only
Merge key in both frames
  1. df1 = pd.DataFrame({'col1': [0, 1], 'col_left':['a', 'b']})
  2. df2 = pd.DataFrame({'col1': [1, 2, 2],'col_right':[2, 2, 2]})
  3. pd.merge(df1, df2, on='col1', how='outer', indicator=True)
  4. Out[44]:
  5. col1 col_left col_right _merge
  6. 0 0.0 a NaN left_only
  7. 1 1.0 b 2.0 both
  8. 2 2.0 NaN 2.0 right_only
  9. 3 2.0 NaN 2.0 right_only

指标参数也将接受字符串参数,在这种情况下,指标函数将使用传递的字符串的值作为指标列的名称。

  1. pd.merge(df1, df2, on='col1', how='outer', indicator='indicator_column')
  2. Out[45]:
  3. col1 col_left col_right indicator_column
  4. 0 0.0 a NaN left_only
  5. 1 1.0 b 2.0 both
  6. 2 2.0 NaN 2.0 right_only
  7. 3 2.0 NaN 2.0 right_only

5、以index为链接键
需要同时设置left_index= True 和 right_index= True,或者left_index设置的同时,right_on指定某个Key。总的来说就是需要指定left、right链接的键,可以同时是key、index或者混合使用。

  1. left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
  2. ....: 'B': ['B0', 'B1', 'B2']},
  3. ....: index=['K0', 'K1', 'K2'])
  4. ....:
  5. right = pd.DataFrame({'C': ['C0', 'C2', 'C3'],
  6. ....: 'D': ['D0', 'D2', 'D3']},
  7. ....: index=['K0', 'K2', 'K3'])
  8. ....:
  9. # 只有K0、K2有对应的值
  10. pd.merge(left,right,how= 'inner',left_index=True,right_index=True)
  11. Out[51]:
  12. A B C D
  13. K0 A0 B0 C0 D0
  14. K2 A2 B2 C2 D2
  15. left = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
  16. 'B': ['B0', 'B1', 'B2', 'B3'],
  17. 'key': ['K0', 'K1', 'K0', 'K1']})
  18. right = pd.DataFrame({'C': ['C0', 'C1'],
  19. 'D': ['D0', 'D1']},
  20. index=['K0', 'K1'])
  21. result = pd.merge(left, right, left_on='key', right_index=True, how='left', sort=False)
  22. # left_on='key', right_index=True
  23. result
  24. Out[54]:
  25. A B key C D
  26. 0 A0 B0 K0 C0 D0
  27. 1 A1 B1 K1 C1 D1
  28. 2 A2 B2 K0 C0 D0
  29. 3 A3 B3 K1 C1 D1

6、sort对链接的键值进行排序:

  1. 紧接着上一例,设置sort= True
  2. result = pd.merge(left, right, left_on='key', right_index=True, how='left', sort=True)
  3. result
  4. Out[57]:
  5. A B key C D
  6. 0 A0 B0 K0 C0 D0
  7. 2 A2 B2 K0 C0 D0
  8. 1 A1 B1 K1 C1 D1
  9. 3 A3 B3 K1 C1 D1

对于多重索引,目前应用较少,就不做深入学习,以后有需要再加。

总的来说,merge的应用场景是针对链接键来进行操作的,链接键可以是index或者column。但是实际应用时一定注意的是left或者right的键值不要重复,这样引来麻烦。