用不匹配的索引将两个系列合二为一

jef*_*fhu 5 python sorting series pandas

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

我尝试了 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)
Run Code Online (Sandbox Code Playgroud)

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

jpp*_*jpp 2

您可以使用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
Run Code Online (Sandbox Code Playgroud)