Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two series into one with mismatching indicies

Tags:

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.

like image 216
jeffhu Avatar asked Jan 05 '19 01:01

jeffhu


People also ask

How do you combine two data series?

Combine Two Series Using pandas. merge() can be used for all database join operations between DataFrame or named series objects. You have to pass an extra parameter “name” to the series in this case. For instance, pd. merge(S1, S2, right_index=True, left_index=True) .

How do I merge two data frames in an index?

Merging Dataframes by index of both the dataframes As both the dataframe contains similar IDs on the index. So, to merge the dataframe on indices pass the left_index & right_index arguments as True i.e. Both the dataframes are merged on index using default Inner Join.


1 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
like image 165
jpp Avatar answered Nov 26 '22 01:11

jpp