pandas学习五
import pandas as pd
import numpy as np
left=pd.DataFrame({
'key':['a','b','c'],
'A':['a1','b1','c1'],
'key2':['a3','b3','c3']})
right=pd.DataFrame({
'key':['a','b','c'],
'B':['a2','b2','c2'],
'key2':['a3','b3','c3']})
merge合并
pd.merge(left,right,on='key')
|
key |
A |
key2_x |
B |
key2_y |
0 |
a |
a1 |
a3 |
a2 |
a3 |
1 |
b |
b1 |
b3 |
b2 |
b3 |
2 |
c |
c1 |
c3 |
c2 |
c3 |
pd.merge(left,right,on=['key','key2'],how='inner',indicator=True)
|
key |
A |
key2 |
B |
_merge |
0 |
a |
a1 |
a3 |
a2 |
both |
1 |
b |
b1 |
b3 |
b2 |
both |
2 |
c |
c1 |
c3 |
c2 |
both |
merge index合并
left=pd.DataFrame({
'key':['a','b','c'],
'A':['a1','b1','c1']},index=['k1','k2','k3'])
right=pd.DataFrame({
'key':['a','b','c'],
'A':['a2','b2','c2']},index=['k1','k2','k3'])
pd.merge(left,right,left_index=True,right_index=True,how='outer')
|
key_x |
A_x |
key_y |
A_y |
k1 |
a |
a1 |
a |
a2 |
k2 |
b |
b1 |
b |
b2 |
k3 |
c |
c1 |
c |
c2 |
pd.merge(left,right,on='key',suffixes=['test1','test2'])
|
key |
Atest1 |
Atest2 |
0 |
a |
a1 |
a2 |
1 |
b |
b1 |
b2 |
2 |
c |
c1 |
c2 |