Home > Back-end >  How to merge 2 pandas Series?
How to merge 2 pandas Series?

Time:10-28

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:

>>> 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.

CodePudding user response:

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
  • Related