[英]Pandas merge / join 2 dataframes
我有两个要加入的数据框,但是,它们不包含完全相同的行。
我在dataframe1中有这个
test1 1
test2 3
test5 4
test6 5
test7 6
这在dataframe2中
test1 4
test3 5
test4 6
test5 3
test6 3
我想要实现的是以下
col1 col2
test1 1 4
test2 3
test3 5
test4 6
test5 4 3
test6 5 3
test7 6
或者
col1 col2
test1 1 4
test2 3 0
test3 0 5
test4 0 6
test5 4 3
test6 5 3
test7 6 0
将pd.merge
与how='outer'
一起使用:
In [1539]: df1
Out[1539]:
col val
0 test1 1
1 test2 3
2 test5 4
3 test6 5
4 test7 6
In [1540]: df2
Out[1540]:
col val
0 test1 4
1 test3 5
2 test4 6
3 test5 3
4 test6 3
In [1541]: df1.merge(df2, on='col', how='outer')
Out[1541]:
col val_x val_y
0 test1 1.0 4.0
1 test2 3.0 NaN
2 test5 4.0 3.0
3 test6 5.0 3.0
4 test7 6.0 NaN
5 test3 NaN 5.0
6 test4 NaN 6.0
In [1542]: df1.merge(df2, on='col', how='outer').fillna(0)
Out[1542]:
col val_x val_y
0 test1 1.0 4.0
1 test2 3.0 0.0
2 test5 4.0 3.0
3 test6 5.0 3.0
4 test7 6.0 0.0
5 test3 0.0 5.0
6 test4 0.0 6.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.