pandas中关于数据合并join,merge

pandas中数据的合并与sql语句类似。主要有函数merge,join等。

merge函数:数据合并,一般是基于通过列索引的数据合并。其有内连接,外连接,左连接,右连接。

 内连接:取两组数据的交集。

c=pd.DataFrame([[3,2,3],[2,3,4]],columns=list("abc"))
b=pd.DataFrame([[2,0,3],[3,2,4],[2,0,9],[0,7,8]],index=["a","b","c","d"],columns=list("abc"))
print(pd.merge(b,c,on="a",how="inner"))
调试:

a b_x c_x b_y c_y
0 2 0 3 3 4
1 2 0 9 3 4
2 3 2 4 2 3

左连接:以左边数据为准,在又测进行查找,找到则拼接,若无补nan

print(pd.merge(b,c,on="a",how="left"))
结果:
a b_x c_x b_y c_y 0
2 0 3 3.0 4.0 1 3 2 4 2.0 3.0 2 2 0 9 3.0 4.0 3 0 7 8 NaN NaN

外连接:取并集,进行拼接


print(pd.merge(b,c,on="a",how="left"))

a b_x c_x b_y c_y 0
2 0.0 3.0 NaN NaN 1 2 0.0 9.0 NaN NaN 2 3 2.0 4.0 2.0 3.0 3 0 7.0 8.0 NaN NaN 4 5 NaN NaN 3.0 4.0

 join函数:根据行索引进行数据合并,默认左连接。

c=pd.DataFrame([["a",4,3],[2,3,4]],columns=list("hkl"))
b=pd.DataFrame([[2,0,3],[3,2,4],[2,0,9],[0,7,8]],columns=list("abc"))
#merge按照列索引,合并数据

print(c.join(b))
结果:
  

  h k l a b c
0 a 4 3 2 0 3
1 2 3 4 3 2 4

原文地址:https://www.cnblogs.com/xuehaiwuya0000/p/11585967.html