当前位置:主页 > 软件编程 > Python代码 >

pandas表连接 索引上的合并方法

时间:2020-12-07 17:31:38 | 栏目:Python代码 | 点击:

如下所示:

left1 = pd.DataFrame({‘key':[‘a','b','a','a','b','c'],'value':range(6)}) 
right1 = pd.DataFrame({‘group_val':[3.5,7]},index = [‘a','b']) 
print(left1) 
print(right1) 
result = pd.merge(left1,right1,left_on='key',right_index=True) 
print(result)

层次化数据的索引

lefth = pd.DataFrame({‘key1':[‘Ohio','Ohio','Ohio','Nevada','Nevada'], 
‘key2':[2000,2001,2002,2001,2002], 
‘data':np.arange(5)}) 
print(lefth) 
righth = pd.DataFrame(np.arange(12).reshape(6,2),index = [[‘Nevada','Nevada','Ohio','Ohio','Ohio','Ohio'], 
[2001,2000,2000,200,2001,2002]]) 
print(righth) 
result = pd.merge(lefth,righth,left_on=[‘key1','key2'],right_index=True) 
print(result)

以上代码如果想改为外部连接 how = ‘outer' 就可以了

同时合并双方索引

left2 = pd.DataFrame([[1,2],[3,4],[5,6]],index=[‘a','c','e'],columns=[‘Ohio','Neveda']) 
right2 = pd.DataFrame([[7,8],[9,10],[11,12],[13,14]],index=[‘b','c','d','e'],columns=[‘Missouri','Alabma']) 
print(left2) 
print(right2) 
result = pd.merge(left2,right2,how='outer',left_index=True,right_index=True) 
print(result)

您可能感兴趣的文章:

相关文章