Pandas 中DataFrame 数据合并 Contract | Merge

最近在工作中,遇到了数据合并、连接的问题,故整理如下,供需要者参考~

参考自:象在舞:https://blog.csdn.net/gdkyxy2013/article/details/80785361


concat

concat:沿着一条轴,将多个对象堆叠到一起

concat方法相当于数据库中的全连接(union all),它不仅可以指定连接的方式(outer join或inner join)还可以指定按照某个轴进行连接。与数据库不同的是,它不会去重,但是可以使用drop_duplicates方法达到去重的效果。

concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, 
       keys=None, levels=None, names=None, verify_integrity=False, copy=True): 

pd.concat()只是单纯的把两个表拼接在一起,参数axis是关键,它用于指定是行还是列,axis默认是0。当axis=0时,pd.concat([obj1, obj2])的效果与obj1.append(obj2)是相同的;当axis=1时,pd.concat([obj1, obj2], axis=1)的效果与pd.merge(obj1, obj2, left_index=True, right_index=True, how=‘outer’)是相同的。

参数介绍:

  • objs:需要连接的对象集合,一般是列表或字典;

  • axis:连接轴向;

  • join:参数为‘outer’或‘inner’;

  • join_axes=[]:指定自定义的索引;

  • keys=[]:创建层次化索引;

  • ignore_index=True:重建索引

案例:

student.csv

   id   name  age    sex
0   1    tom   23    man
1   2   john   33    man
2   3  alice   22  woman
3   4   jack   42    man
4   5   saex   22  woman
5   6   jmas   21    man
6   7  jjban   34    man
7   8  alicn   22  woman

score.csv

   id   name  score
0   1    tom     89
1   2   john     90
2   3  alice     78
3   4   jack     99
4   5   saex     87

使用contract进行连接,注意contract([df1,df2]) 的这种写法,join可选outer/inner

contract_pd = pd.concat([student_pd,score_pd],join='outer', ignore_index=True)

   id   name   age    sex  score
0   1    tom  23.0    man    NaN
1   2   john  33.0    man    NaN
2   3  alice  22.0  woman    NaN
3   4   jack  42.0    man    NaN
4   5   saex  22.0  woman    NaN
5   6   jmas  21.0    man    NaN
6   7  jjban  34.0    man    NaN
7   8  alicn  22.0  woman    NaN
0   1    tom   NaN    NaN   89.0
1   2   john   NaN    NaN   90.0
2   3  alice   NaN    NaN   78.0
3   4   jack   NaN    NaN   99.0
4   5   saex   NaN    NaN   87.0
5   6   jmas   NaN    NaN   33.0

contract_pd = pd.concat([student_pd,score_pd],join='inner', ignore_index=True)
    id   name
0    1    tom
1    2   john
2    3  alice
3    4   jack
4    5   saex
5    6   jmas
6    7  jjban
7    8  alicn
8    1    tom
9    2   john
10   3  alice
11   4   jack
12   5   saex
13   6   jmas


merge 通过键拼接列

类似于 关系型数据库 的连接方式,可以根据一个或多个键将不同的DatFrame连接起来。该函数的典型应用场景是,针对同一个主键存在两张不同字段的表,根据主键整合到一张表里面。

merge(left, right, how='inner', on=None, left_on=None, right_on=None,  
      left_index=False, right_index=False, sort=True,  
      suffixes=('_x', '_y'), copy=True, indicator=False)

参数介绍:

  • left和right:两个不同的DataFrame;

  • how:连接方式,有inner、left、right、outer,默认为inner;

  • on:指的是用于连接的列索引名称,必须存在于左右两个DataFrame中,如果没有指定且其他参数也没有指定,则以两个DataFrame列名交集作为连接键;

  • left_on:左侧DataFrame中用于连接键的列名,这个参数左右列名不同但代表的含义相同时非常的有用;

  • right_on:右侧DataFrame中用于连接键的列名;

  • left_index:使用左侧DataFrame中的行索引作为连接键;

  • right_index:使用右侧DataFrame中的行索引作为连接键;

  • sort:默认为True,将合并的数据进行排序,设置为False可以提高性能;

  • suffixes:字符串值组成的元组,用于指定当左右DataFrame存在相同列名时在列名后面附加的后缀名称,默认为(’_x’, ‘_y’);

  • copy:默认为True,总是将数据复制到数据结构中,设置为False可以提高性能;

示例:


# 1.默认以重叠的列名当做连接键
contract_pd = pd.merge(student_pd,score_pd,how="inner",sort=True)
   id name_x  age    sex name_y  score
0   1    tom   23    man    tom     89
1   2   john   33    man   john     90
2   3  alice   22  woman  alice     78
3   4   jack   42    man   jack     99
4   5   saex   22  woman   saex     87
5   6   jmas   21    man   jmas     33


# 2.默认做inner连接(取key的交集),连接方式还有(left,right,outer),制定连接方式加参数:how=''
contract_pd = pd.merge(student_pd,score_pd,how="left",on='id',sort=True)
   id name_x  age    sex name_y  score
0   1    tom   23    man    tom   89.0
1   2   john   33    man   john   90.0
2   3  alice   22  woman  alice   78.0
3   4   jack   42    man   jack   99.0
4   5   saex   22  woman   saex   87.0
5   6   jmas   21    man   jmas   33.0
6   7  jjban   34    man    NaN    NaN
7   8  alicn   22  woman    NaN    NaN

# 3. 执行on 的时候不能够指定left_on 或者right_on
contract_pd = pd.merge(student_pd, score_pd, how="left", left_on='id', right_on='id', sort=True)
   id name_x  age    sex name_y  score
0   1    tom   23    man    tom   89.0
1   2   john   33    man   john   90.0
2   3  alice   22  woman  alice   78.0
3   4   jack   42    man   jack   99.0
4   5   saex   22  woman   saex   87.0
5   6   jmas   21    man   jmas   33.0
6   7  jjban   34    man    NaN    NaN
7   8  alicn   22  woman    NaN    NaN

按照条件取出merge的结果:

# 取出score为NaN的记录
allsed = contract_pd.loc[contract_pd.score.isna()]
   id name_x  age    sex name_y  score
6   7  jjban   34    man    NaN    NaN
7   8  alicn   22  woman    NaN    NaN

# 取出score 为非NaN的记录
allsed = contract_pd.loc[~contract_pd.score.isna()]
   id name_x  age    sex name_y  score
0   1    tom   23    man    tom   89.0
1   2   john   33    man   john   90.0
2   3  alice   22  woman  alice   78.0
3   4   jack   42    man   jack   99.0
4   5   saex   22  woman   saex   87.0
5   6   jmas   21    man   jmas   33.0

# 对结果进行去重
allsed.drop_duplicates()

作用上lambda函数:

tag_pd = pd.read_csv("tags.csv")
   id                           tags
0   1  1234|2345|3456|2348|7865|1357
1   2  1234|2345|3456|2348|7865|1357
2   3  1234|2345|3456|2348|7865|1357
3   4  1234|2345|3456|2348|7865|1357
4   5  1234|2345|3456|2348|7865|1357
5   6  1234|2345|3456|2348|7865|1357


tag_pd['idss'] = tag_pd.tags.apply(lambda x:x.split('|'))
   id                           tags                                  idss
0   1  1234|2345|3456|2348|7865|1357  [1234, 2345, 3456, 2348, 7865, 1357]
1   2  1234|2345|3456|2348|7865|1357  [1234, 2345, 3456, 2348, 7865, 1357]
2   3  1234|2345|3456|2348|7865|1357  [1234, 2345, 3456, 2348, 7865, 1357]
3   4  1234|2345|3456|2348|7865|1357  [1234, 2345, 3456, 2348, 7865, 1357]
4   5  1234|2345|3456|2348|7865|1357  [1234, 2345, 3456, 2348, 7865, 1357]

总结:

  1. contract 类似于关系型数据库中的union all 操作
  2. merge 类似于关系型数据库中的 inner join 、left join、right join 操作

猜你喜欢

转载自blog.csdn.net/qq_43081842/article/details/110354985
今日推荐