python - 有没有一种有效的方法来合并 Pandas 中两个排序的数据帧,保持排序?

标签 python numpy pandas

如果我有两个已按兼容键排序的数据帧(或系列),我希望能够廉价地将它们合并在一起并保持排序。除了通过 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 数组相关的讨论,建议使用“交错”方法,但我还没有找到好的答案。

最佳答案

如果我们将问题限制在只有一列的 ab 上,那么我会走这条路:

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/

相关文章:

python - 带浮点参数的范围()

python - 在python中提取文件中的随机行而不将文件加载到RAM中

python - 在带有标记的列和行的 python 字典中创建矩阵

python - 使用 3 列数据操作 pandas 数据框

python - 将百分比字符串转换为 pandas read_csv 中的 float

python - 如何阅读周三 Oct 02 09 :37:43 BST 2019 to datetime format using pandas?

python - 删除具有 na 值的行

python - 我正在使用 Python3,我想使用 RabbitMQ

python - 修改 numpy 数组以获取元素之间值的最小数量

python-3.x - Python : Running nested loop, 2D 移动窗口,并行