温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Pandas怎么实现表连接

发布时间:2021-08-17 20:02:49 来源:亿速云 阅读:170 作者:chen 栏目:云计算

这篇文章主要介绍“Pandas怎么实现表连接”,在日常操作中,相信很多人在Pandas怎么实现表连接问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Pandas怎么实现表连接”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

连接对象(Concatenating)

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

join有两个参数inner(内连)和outer(外连)
ignore_index:是否忽略索引,默认不忽略,此时会按照索引连接。
join_axes:使用哪个数据框的索引
keys:复合索引

横向连接

In [1]: df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],   ...:                     'B': ['B0', 'B1', 'B2', 'B3'],   ...:                     'C': ['C0', 'C1', 'C2', 'C3'],   ...:                     'D': ['D0', 'D1', 'D2', 'D3']},   ...:                     index=[0, 1, 2, 3])   ...: 
In [8]: df4 = pd.DataFrame({'B': ['B2', 'B3', 'B6', 'B7'],   ...:                  'D': ['D2', 'D3', 'D6', 'D7'],   ...:                  'F': ['F2', 'F3', 'F6', 'F7']},   ...:                 index=[2, 3, 6, 7])   ...: 
result = pd.concat([df1, df4], axis=1, join_axes=[df1.index])

Pandas怎么实现表连接

纵向连接

In [15]: result = pd.concat([df1, df4], ignore_index=True)
Pandas怎么实现表连接

append函数更加有效率

数据库形式的连接(joining/merging)

这个语法是专门为那些使用SQL数据的人群设置的

pd.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:右数据表
on:以哪一列为标准做联表,如果没有输入参数,则会以共有的索引作为依据
left_on:以左边的数据框作为join key
right_on:以右边的数据框作为join key
left_index:以左边的索引作为join key
right_index:以右边的索引作为join key
how:left right out inner,默认为inner
sort:通过join key对结果进行排序
suffixes:
copy:
indicator:

merge同时也是一个对象方法,对象默认是左联表。而join实例方法则是默认以索引做为连接方法。

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

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

In [40]: result = pd.merge(left, right, on='key')

Pandas怎么实现表连接
使用indicator可以监视连接的状态

In [48]: df1 = pd.DataFrame({'col1': [0, 1], 'col_left':['a', 'b']})

In [49]: df2 = pd.DataFrame({'col1': [1, 2, 2],'col_right':[2, 2, 2]})

In [50]: pd.merge(df1, df2, on='col1', how='outer', indicator=True)Out[50]: 
   col1 col_left  col_right      _merge0     0        a        NaN   left_only1     1        b        2.0        both2     2      NaN        2.0  right_only3     2      NaN        2.0  right_only

到此,关于“Pandas怎么实现表连接”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI