我想以一种不同寻常的方式合并两个df。
有问题的df:
df1:
Index colA
2012-01-02 1
2012-01-05 2
2012-01-10 3
2012-01-10 4
然后是df2:
Index colB
2012-01-01 6
2012-01-05 7
2012-01-08 8
2012-01-10 9
输出:
Index colA colB
2012-01-01 NaN 6
2012-01-02 1 NaN
2012-01-05 2 7
2012-01-08 NaN 8
2012-01-10 3 9
2012-01-10 4 NaN
当我自己尝试使用pd.merge()
和其他工具来执行此操作时,我不能这样做,因为日期显然不是索引唯一的。
任何建议如何获得预期的行为?
谢谢
答案 0 :(得分:3)
您可能需要使用cumcount
df1=df1.assign(key=df1.groupby('Index').cumcount())
df2=df2.assign(key=df2.groupby('Index').cumcount())
fdf=df1.merge(df2,how='outer').drop('key',1).sort_values('Index')
fdf
Out[104]:
Index colA colB
4 2012-01-01 NaN 6.0
0 2012-01-02 1.0 NaN
1 2012-01-05 2.0 7.0
5 2012-01-08 NaN 8.0
2 2012-01-10 3.0 9.0
3 2012-01-10 4.0 NaN
答案 1 :(得分:0)
使用join()
应该可以
df1.join(df2, how='outer', sort=True)