How to append a pandas Series object to another Series in Python?


The basic operation of pandas.Series.append() method is used to concatenate a series with another series. And it will return a new series with resultant elements.

This append() method has some parameters like to_append, ignore_index, and verify_integrity to concatenate two pandas series objects.

Example 1

# import the required packages
import pandas as pd
import numpy as np

series1 = pd.Series(np.random.randint(1,100,5))
print(series1)

series2 = pd.Series(np.random.randint(1,100,4))
print(series2)

# apply append method on series
result = series1.append(series2)

print("Resultant series: ",result)

Explanation

In the following example, we have appended a pandas series object “series1” with another series object “series2”. we haven’t applied any parameter inputs so the default values are taken.

Output

0 89
1 69
2 20
3  4
4 77
dtype: int64

0 48
1 87
2 77
3 75
dtype: int64

Resultant series:
0 89
1 69
2 20

3  4
4 77
0 48
1 87
2 77
3 75
dtype: int32

In this above block, we can see both the initial series objects and also the output of the append() method. As we haven’t provided any parameter values, it takes the default once’s. Due to this, we can see the duplicate index labels in the resultant series object.

Example 2

# import the required packages
import pandas as pd
import numpy as np

series1 = pd.Series([1,2,3,4,5])
print(series1)

series2 = pd.Series([3,5,2,7])
print(series2)

# apply append method on series
result = series1.append(series2, ignore_index=True)

print("Resultant series: ",result)

Explanation

Let’s take another set of pandas series objects to apply the append() method. For the following series object, we haven’t defined any index labels initially.

Here we applied the boolean value ”True” to the ignore_index parameter so that we can eliminate the duplicate index labels.

Output

0 1
1 2
2 3
3 4
4 5
dtype: int64

0 3
1 5
2 2
3 7
dtype: int64

Resultant series:
0 1
1 2
2 3
3 4
4 5
5 3
6 5
7 2
8 7
dtype: int64

In the above output block, we can observe initial series objects and also the output of the append() method.

Updated on: 09-Mar-2022

481 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements