Combining two series into one with mismatching indicies

Viewed 77

I'm trying to merge two series with mismatching indicies into one, and I'm wondering what best practices are.

I tried combine_first but I'm getting an issue where combining a series [0, 24, ...] with a series [1, 25, ...] should give a series with indicies [0, 1, 24, 25, ...] but instead I'm getting [0, 12, 24, 36, ...]

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

I just want two series with mutually exclusive indicies to be combined into a single series that contain both indicies in the correct sorted order. Kind of like a zipper.

2 Answers

You can use pd.concat followed by 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

Using align

sum(s1.align(s2,fill_value=0))
0     1.0
1     5.0
24    2.0
25    6.0
30    3.0
35    7.0
38    8.0
40    4.0
dtype: float64
Related