Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge 2 pandas Series?

I have 2 pandas Series (s1, and s2) like this:

import pandas as pd

index1 = list(range(6))
index2 = list(range(2, 8))

data1 = [7, 6, 1, 9, 3, 4]
data2 =       [1, 9, 3, 4, 10, 12]

s1 = pd.Series(data=data1, index=index1)
s2 = pd.Series(data=data2, index=index2)

s1 and s2 have some common indices. And they have the same value at the corresponding index.

How can I use s1 and s2 to create a new Series s3 that contains the following content:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> print(s3)
0     7
1     6
2     1
3     9
4     3
5     4
6    10
7    12

Here’s another example of the merge:

import pandas as pd

index1 = list(range(6))
index2 = list(range(8, 14))

data1 = [7, 6, 1, 9, 3, 4]
data2 = [7, 2, 5, 6, 10, 12]

s1 = pd.Series(data=data1, index=index1)
s2 = pd.Series(data=data2, index=index2)

s3 = merge(s1, s2)

print(s3)

# 0      7
# 1      6
# 2      1
# 3      9
# 4      3
# 5      4
# 8      7
# 9      2
# 10     5
# 11     6
# 12    10
# 13    12
# dtype: int64

In this example, s1 and s2 don’t have common indices.

>Solution :

If your indices are already aligned, then you can use a simple combine_first:

out = s1.combine_first(s2).convert_dtypes()

output:

0     7
1     6
2     1
3     9
4     3
5     4
6    10
7    12
dtype: Int64

second example output:

0      7
1      6
2      1
3      9
4      3
5      4
8      7
9      2
10     5
11     6
12    10
13    12
dtype: Int64
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading