pandas表连接 索引上的合并方法
程序员文章站
2022-06-11 22:36:49
如下所示:
left1 = pd.dataframe({‘key':[‘a','b','a','a','b','c'],'value':range(6)})...
如下所示:
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)
以上这篇pandas表连接 索引上的合并方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
推荐阅读