首页 > 解决方案 > 将两个系列合并为一个索引不匹配的系列

问题描述

我正在尝试将两个索引不匹配的系列合并为一个,我想知道最佳实践是什么。

我尝试了 combine_first 但我遇到了一个问题,将系列 [0, 24, ...] 与系列 [1, 25, ...] 组合应该给出一个带有索引 [0, 1, 24, 25, ...] 但我得到 [0, 12, 24, 36, ...]

for row in all_rows:
    base_col = base_col.combine_first(row)

我只想将具有互斥索引的两个系列组合成一个系列,其中包含两个索引的正确排序顺序。有点像拉链。

标签: pythonpandassortingseries

解决方案


您可以使用pd.concat后跟sort_index

s1 = pd.Series([1, 2, 3, 4], index=[0, 24, 30, 40])
s2 = pd.Series([5, 6, 7, 8], index=[1, 25, 35, 38])

s = pd.concat([s1, s2]).sort_index()

print(s)

0     1
1     5
24    2
25    6
30    3
35    7
38    8
40    4
dtype: int64

推荐阅读