Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you Merge 2 Series in Pandas

I have the following:

s1 = pd.Series([1, 2], index=['A', 'B'])

s2 = pd.Series([3, 4], index=['C', 'D'])

I want to combine s1 and s2 to create s3 which is:

s3 = pd.Series([1, 2, 3, 4], index=['A', 'B', 'C', 'D'])

NB: There is no index overlap

like image 289
Suminda Sirinath S. Dharmasena Avatar asked Feb 28 '17 16:02

Suminda Sirinath S. Dharmasena


2 Answers

You can use concat(), it automatically executes an outer join:

pd.concat([s1, s2])

result:

A    1
B    2
C    3
D    4
dtype: int64
like image 95
elcombato Avatar answered Oct 24 '22 07:10

elcombato


Solution from @EdChum works well, but numpy stacking is faster when you don't need to worry about index alignment.

In [18]: pd.DataFrame( np.hstack((s1.values, s2.values))  , index=np.hstack((s1.index.values, s2.index.values)))
Out[18]: 
   0
A  1
B  2
C  3
D  4

In [19]: %timeit pd.concat([s1, s2])

1000 loops, best of 3: 1.31 ms per loop

In [21]: %timeit pd.DataFrame( np.hstack((s1.values, s2.values)  ), index=np.hstack((s1.index.values, s2.index.values)))

10000 loops, best of 3: 214 µs per loop
like image 3
clocker Avatar answered Oct 24 '22 07:10

clocker