Pandas 数据处理 | 多个数据表怎么合并(merge),你了解么?

Pands 两个数据列表合并方法总结;

merge() 函数用于合并两个 DataFrame 对象或 Series,数据处理时经常会用到这个函数,官网给出该函数的定义如下:

pandas.merge(left, right, how: str = ‘inner’, on=None, left_on=None, right_on=None, left_index: bool = False, right_index: bool = False, sort: bool = False, suffixes=’_x’, ‘_y’, copy: bool = True, indicator: bool = False, validate=None)

先介绍一下 各参数的含义作用;

left 左边的 DataFrame
right 右边要合并的 DataFrame
how 合并方式,一共四种: left,right,inner,outer,默认为 inner
left 仅使用来自左边frame的键进行匹配;
right 仅使用来自右边frame 的键进行匹配;
outer 取来自左右frame 键的并集;匹配不到的话元素设为Null
inner 取来自左右frame 键的交集,匹配不到的话元素丢失;
on label or list
选取合并的基准列也就是键名,前提该键名在两个 DataFrames 中有存在,如果未设置的话,默认为左右两个 DataFrame 的列名交集;
left_on label、list、array_list
左边 DataFrame 中的列或索引级别作为键;可为列名或索引名
right_on lable、list、array_list
右边DataFrame中 的列或索引级别作为键;可为列名或索引名
left_index bool,默认False
用左边的index 作为连接键;若为多 index, 则右侧的 DataFrame 中的连接键数必须与级别数相匹配;
right_index bool,默认为False
用右边的 index 作为连接键;若为多index,则左侧的 DataFrame 中的连接键数必须与级别数相匹配;
sort bool,默认False
对合并之后的 DataFrame 对 连接键以字典字母顺序进行和兴;
suffixes tuple of (str,str),默认(_x,_y)
对左右两边出现重复列名分别加入后缀名用于区分;若设置(False,False)出现类名重叠则会抛出异常
copy bool,默认为 True
为 Flase的话,避免复制
indicator 布尔或 str,默认为False
为True 使,对最后的 DataFrame 加入新列,列名为"_merge" 有关每一行的匹配的基本信息
对于仅在 左边匹配成功时,取值为 left_only,仅出现在右边匹配成功时则 为 right_only;两边都匹配成功时则为 both;
validate str、optional
如果指定,检查merge 是否为指定类型
1:1 ,检查合并键是否在左右数据集中是唯一值;
1:m ,检查合并键是否在左边数据集中是唯一值
m:1 ,检查合并键是否在右边数据集是唯一值

上面是对参数的一些介绍,下面将围绕这些参数结合一些实例操作,详细说明一下 merge() 函数的具体使用,分为几个部分:

左右 DataFrame 有相同 key 值时;

**设置参数 on 实现两个DataFrame 的简单合并 **

In [1]: import pandas as pd

In [2]: data1 =pd.DataFrame({
    
    'key':['K0','K1','K2','K3'],
   ...:                 'A':['A0','A1','A2','A3'],
   ...:                 'B':['B0','B1','B2','B3']})

In [3]: data2 = pd.DataFrame({
    
    'key':['K0','K1','K2','K3'],})

In [4]: data2 = pd.DataFrame({
    
    'key':['K0','K1','K2','K3'],
   ...:                         'C':['C0','C1','C2','C3'],
   ...:                         'D':['D0','D1','D2','D3']})

In [5]: result = pd.merge(data1,data2,on = 'key')

In [6]: result
Out[6]:
  key   A   B   C   D
0  K0  A0  B0  C0  D0
1  K1  A1  B1  C1  D1
2  K2  A2  B2  C2  D2
3  K3  A3  B3  C3  D3

merge 四种合并方式

how = “left” 仅以左边的key为基准,右侧匹配失败元素设为 Null
how = “right” 仅以右边的key 为基准,左侧匹配失败元素设为Null
how = “outer” 以左右两边关键词并集为基准,匹配失败元素设为Null
how = “inner” 左右两边关键词的交集作为基准,匹配失败的话直接 delete 该行
In [7]: data1 =pd.DataFrame({
    
    'a':['a1','a2','a3'],
   ...:                     'b':['b1','b2','b3'],
   ...:                     'key':['a','b','c'],
   ...:                     'key1':['d','e','f']})
   ...:
   ...:

In [8]: data2 = pd.DataFrame({
    
    'c':['c1','c2','c3'],
   ...:                         'd':['d1','d2','d3'],
   ...:                         'key':['a','b','a'],
   ...:                         'key1':['d','e','e']})

**how= “left” 合并 **

以左边的 DataFrame 的 key 为基准,右边出现匹配失败的用 NaN 代替,出现多余 Key 表单所在的行部分直接被删除

Snipaste_2020-07-18_08-21-29.png

  • 图表解读:
    • red : 表示所在行被剔除;
    • blue :代表所在行被保留;
    • green : 表示误配的值用 NaNs 来代替;
In [9]: # how = left,以左边键为基准

In [10]: pd.merge(data1,data2,how ="left",on = ['key','key1'])
Out[10]:
    a   b key key1    c    d
0  a1  b1   a    d   c1   d1
1  a2  b2   b    e   c2   d2
2  a3  b3   c    f  NaN  NaN

how ="right"

以右边 DataFrame 的 key 为基准,用法与 how=“left” 相似,方向相反;

Snipaste_2020-07-18_08-21-51.png

In [11]: #how = right ,以右边为基准

In [12]: pd.merge(data1,data2,how = 'right',on =['key','key1'])
Out[12]:
     a    b key key1   c   d
0   a1   b1   a    d  c1  d1
1   a2   b2   b    e  c2  d2
2  NaN  NaN   a    e  c3  d3

how ="inner"

此合并方法在用的频率较高以左右两边 DataFrame 共有的 key 为基准,匹配成功的保留,匹配失败所在的行全部删除;

inner.png

In [16]: # how = inner,取左右交集;

In [17]: pd.merge(data1,data2,how ='inner',on = ['key','key1'])
Out[17]:
    a   b key key1   c   d
0  a1  b1   a    d  c1  d1
1  a2  b2   b    e  c2  d2

how ="outer"

与 how=“inner” 用法对应,以左右两边 DataFrame 共有的 key 为基准,匹配成功的保留,匹配失败的键值以 Nan 进行替换;

outrt.png

In [13]: # how = outer,r取左右两边并集
    
In [15]: pd.merge(data1,data2,how ='outer',on = ['key','key1'])
Out[15]:
     a    b key key1    c    d
0   a1   b1   a    d   c1   d1
1   a2   b2   b    e   c2   d2
2   a3   b3   c    f  NaN  NaN
3  NaN  NaN   a    e   c3   d3

DataFrame 具有不同 key 值合并

当要合并的两个 DataFrame 具有不同 key 值时,这里需要用到 left_on、right_on 参数,分别用来指定左右 DataFrame 的列名;

left_on 、right_on 为key 作为基准

left_on 选取 key 名时,需要对 right_on 设置对应 键名,且需要保证 len(left_on) == len(right_on),

加入 suffixes 参数,是因为左右具有相同列名( value ),保证合并后的 列名都不一样

In [18]: df1 = pd.DataFrame({
    
    'lkey': ['foo', 'bar', 'baz', 'foo'],
    ...:                     'value': [1, 2, 3, 5]})

In [19]: df2 = pd.DataFrame({
    
    'rkey': ['foo', 'bar', 'baz', 'foo'],
    ...:                     'value': [5, 6, 7, 8]})

In [20]: df1
Out[20]:
  lkey  value
0  foo      1
1  bar      2
2  baz      3
3  foo      5

In [21]: df2
Out[21]:
  rkey  value
0  foo      5
1  bar      6
2  baz      7
3  foo      8

In [22]: pd.merge(df1,df2,left_on ='lkey')


In [23]: pd.merge(df1,df2,left_on ='lkey',right_on ='rkey')
Out[23]:
  lkey  value_x rkey  value_y
0  foo        1  foo        5
1  foo        1  foo        8
2  foo        5  foo        5
3  foo        5  foo        8
4  bar        2  bar        6
5  baz        3  baz        7

# 设置 suffixes 参数之后
In [24]: pd.merge(df1,df2,left_on ='lkey',right_on ='rkey',suffixes=("_lf","_rf"))
Out[24]:
  lkey  value_lf rkey  value_rf
0  foo         1  foo         5
1  foo         1  foo         8
2  foo         5  foo         5
3  foo         5  foo         8
4  bar         2  bar         6
5  baz         3  baz         7

操作前需要保证 键值长度相等,len(left_on) == len(right_on);否则会出现下面错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-0660dac837b1> in <module>
----> 1 pd.merge(df1,df2,left_on ='lkey')

~\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py in merge(left, right, how, on, left_on, right_on, left_index, right_index, sort, suffixes, copy, indicator, validate)
     79         copy=copy,
     80         indicator=indicator,
---> 81         validate=validate,
     82     )
     83     return op.get_result()

~\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py in __init__(self, left, right, how, on, left_on, right_on, axis, left_index, right_index, sort, suffixes, copy, indicator, validate)
    617             warnings.warn(msg, UserWarning)
    618
--> 619         self._validate_specification()
    620
    621         # note this function has side effects

~\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py in _validate_specification(self)
   1221                     )
   1222                 self.left_on = [None] * n
-> 1223         if len(self.right_on) != len(self.left_on):
   1224             raise ValueError("len(right_on) must equal len(left_on)")
   1225

TypeError: object of type 'NoneType' has no len()

以索引列( index )作为合并基准

merge() 也可以以索引列作为合并基准,此时用到两个参数 left_on、right_on;都设为 True;

np.random.seed([3, 14])
left = pd.DataFrame({
    
    'value': np.random.randn(4)}, index=['A', 'B', 'C', 'D'])    
right = pd.DataFrame({
    
    'value': np.random.randn(4)}, index=['B', 'D', 'E', 'F'])
left.index.name = right.index.name = 'idxkey'

left
           value
idxkey          
A      -0.602923
B      -0.402655
C       0.302329
D      -0.524349

right

           value
idxkey          
B       0.543843
D       0.013135
E      -0.326498
F       1.385076



left.merge(right, left_index=True, right_index=True)


         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

同时合并多个 DataFrame

合并多个 DataFrame 的方法有很多种,这里列出下面几条:

低效 merge()

df1.merge(df2, ...).merge(df3, ...)

方法合并时需要设置多个参数,并且较为低效;

pd.concat() 进行合并

pd.concat() 可以对多个 DataFrame 进行同时合并,合并方法与前面提到的 merge() 四种方法相同,区别是前面以关键字 how 衔接,这里以 join 作为衔接参数:

np.random.seed(0)
A = pd.DataFrame({
    
    'key': ['A', 'B', 'C', 'D'], 'valueA': np.random.randn(4)})    
B = pd.DataFrame({
    
    'key': ['B', 'D', 'E', 'F'], 'valueB': np.random.randn(4)})
C = pd.DataFrame({
    
    'key': ['D', 'E', 'J', 'C'], 'valueC': np.ones(4)})
dfs = [A, B, C] 

# Note, the "key" column values are unique, so the index is unique.
A2 = A.set_index('key')
B2 = B.set_index('key')
C2 = C.set_index('key')


pd.concat(dfs2, axis=1, sort=False, join='inner')

       valueA    valueB  valueC
key                            
D    2.240893 -0.977278     1.0

4, indicator 参数

indicator 参数(设置为 True);用来表示 DataFrame 会添加新的一列 ,列名为_merge; 来表示各行的合并类型信息。

In [25]: pd.merge(data1,data2,how ='outer',on = ['key','key1'],indicator = True)
Out[25]:
     a    b key key1    c    d      _merge
0   a1   b1   a    d   c1   d1        both
1   a2   b2   b    e   c2   d2        both
2   a3   b3   c    f  NaN  NaN   left_only
3  NaN  NaN   a    e   c3   d3  right_only

indicator 也可以设为 String ,自定义列名

In [27]: pd.merge(data1,data2,how ='outer',on = ['key','key1'],indicator ="col_info")
Out[27]:
     a    b key key1    c    d    col_info
0   a1   b1   a    d   c1   d1        both
1   a2   b2   b    e   c2   d2        both
2   a3   b3   c    f  NaN  NaN   left_only
3  NaN  NaN   a    e   c3   d3  right_only

好了,以上就是本文对 merge() 用法的介绍,关于 merge() 更深入、全面的用法,以后再加讨论

最后感谢大家阅读!

Reference:

1,https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

2,https://stackoverflow.com/questions/53645882/pandas-merging-101

文章首发于公众号(Z先生点记

猜你喜欢

转载自blog.csdn.net/weixin_42512684/article/details/107461520