如果我有两个已按兼容键排序的数据帧(或系列),我希望能够廉价地将它们合并在一起并保持排序。除了通过 concat() 和显式 sort() 之外,我看不到其他方法
a = pd.DataFrame([0,1,2,3], index=[1,2,3,5], columns=['x'])
b = pd.DataFrame([4,5,6,7], index=[0,1,4,6], columns=['x'])
print pd.concat([a,b])
print pd.concat([a,b]).sort()
x
1 0
2 1
3 2
5 3
0 4
1 5
4 6
6 7
x
0 4
1 0
1 5
2 1
3 2
4 6
5 3
6 7
似乎有一些与 numpy 数组相关的讨论,建议使用“交错”方法,但我还没有找到好的答案。
最佳答案
如果我们将问题限制在只有一列的 a
和 b
上,那么我会走这条路:
s = a.merge(b, how='outer', left_index=True, right_index=True)
s.stack().reset_index(level=1, drop=True)
关于python - 有没有一种有效的方法来合并 Pandas 中两个排序的数据帧,保持排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16318329/