python数据分析之pandas(8)数据合并

1. merge函数指定合并列

>>> import pandas as pd
>>> frame1 = pd.DataFrame({'id': ['ball', 'pencil', 'pen', 'mug', 'ashtray'
olor': ['white', 'red', 'red', 'black', 'green'], 'brand': ['OMG', 'ABC', '
 'POD', 'POD']})
>>> frame1
  brand  color       id
0   OMG  white     ball
1   ABC    red   pencil
2   ABC    red      pen
3   POD  black      mug
4   POD  green  ashtray
>>> frame2 = pd.DataFrame({'id': ['pencil', 'pencil', 'ball', 'pen'], 'bran
'OMG', 'POD', 'ABC', 'POD']})
>>> frame2
  brand      id
0   OMG  pencil
1   POD  pencil
2   ABC    ball
3   POD     pen
>>> pd.merge(frame1, frame2, on='id')
  brand_x  color      id brand_y
0     OMG  white    ball     ABC
1     ABC    red  pencil     OMG
2     ABC    red  pencil     POD
3     ABC    red     pen     POD
>>>

从以上结果可以看出,id和brand为共同列。合并后会产生brand_x和brand_y 2个新列

2. 左连接,右连接和外连接

默认为内连接,同时可以设置:

how='inner' //内连接,2个结果取交集

how='left' //左连接,即合并列结果为左边列

how='right' //右连接,合并结果为外连接

how='outer' //外连接,合并结果为2列结果的并集

3.通过left_on和right_on合并不同列

pd.merge(frame1, frame2, left_on='id', right_on='sid')

4.合并多个键

pd.merge(frame1, frame2, on=['id', 'brand'], how='outer')

5.根据索引合并

>>> frame2.columns = ['brand2', 'id2']
>>> frame1.join(frame2)
  brand  color       id brand2     id2
0   OMG  white     ball    OMG  pencil
1   ABC    red   pencil    POD  pencil
2   ABC    red      pen    ABC    ball
3   POD  black      mug    POD     pen
4   POD  green  ashtray    NaN     NaN
>>>

由于frame2中有和frame1重复的列名,所以先重命名,之后作为新列合并到frame1中,

超过索引序号的为NaN

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值