What does the add() method do in the pandas series?

PandasServer Side ProgrammingProgramming

The basic operation of this add() method in series is used to add a series with another series, or with a list of values, or with a single integer. And it will return a new series with resultant elements.

It supports the substitution of fill_values for handling missing data. We can fill Nan Values using the fill_value parameter of the series.add() method.

If you want to add a series with a list, then the elements in the list must be equal to the number of elements in the series.


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

series = pd.Series(np.random.randint(1,100,10))

# add series with a single value
result = series.add(2)

print("\nResultant series: ",result, sep='\n')


In the following example, we have calculated the addition of a series with an integer number 2. Our pandas series object “series” which is created by the NumPy random.randint function with 10 values.

Then we used the pandas Series function add() to calculate the addition of our random integer series with an integer value 2, and the resultant series is stored in the result variable.


0   78
1    8
2   27
3   86
4   15
5   39
6   27
7   85
8    8
9   64
dtype: int32

Resultant series:
0   80
1   10
2   29
3   88
4   17
5   41
6   29
7   87
8   10
9   66
dtype: int32

In this above block, we can see both the output of the initial series object which is created by random integer values, and another is the resultant series object from the add() function pandas Series.


# impor the pandas package
import pandas as pd

series = pd.Series([2,8,3,93,78,1])

# adding a series with a list of values
result = series.add([1,2,3,4,5,6])

print("\nResultant series: ",result, sep='\n')


The following example is for performing the addition operation on a series with a python list data using the Pandas Series.add() function.


0   2
1   8
2   3
3  93
4  78
5   1
dtype: int64

Resultant series:
0   3
1  10
2   6
3  97
4  83
5   7
dtype: int64

Here we can see the data present in our initial series object which is created by using python list, and as well as we can see the resultant series object from the series.add() method. The list must be equal to the series otherwise it will raise an error (ValueError).

Updated on 18-Nov-2021 10:25:12