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