Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Pandas Series add() Method

In this tutorial, we will discuss and learn the pandas Series.add() method. By using this method, we can add the Series with other Series, scalar value. When this method applied to the Series, it returns a Series. This method supports the filling NaN values using the parameter fill_value.

The below is the syntax of the Series.add() method.

Syntax

Series.add(other, level=None, fill_value=None, axis=0)

Parameters

other: It can be a Series or scalar value.

fill_value: It can be a None or float value, and the default is None (NaN). It fills the null or missing values.

level: It represents the int or name. It broadcasts across a level, matching Index values on the passed MultiIndex level.

Example: Add a Value to the Series

Here, in this example, we are adding the Series with the scalar using the Series.add() method. The elements in the Series are added with the scalar value '2' one by one and returns the Series.

#importing pandas as pd
import pandas as pd
#creating Series
s = pd.Series([1,2,3,4])
print("-----Series-----")
print(s)
print("-------------------")
print(s.add(2))


-----Series-----
0 1
1 2
2 3
3 4
dtype: int64
-------------------
0 3
1 4
2 5
3 6
dtype: int64

Example: Add a Series with other Series

Here, in this example, we will add the Series with other Series using the Series.add() method. See the below example.

#importing pandas as pd
import pandas as pd
#creating Series
s_1= pd.Series([1,2,3])
s_2= pd.Series([4,5,6])
print("------After adding two series the result is------")
print(s_1.add(s_2))


------After adding two series the result is------
0 5
1 7
2 9
dtype: int64

Example: Set fill_value='n' in the Series.add() method

By passing the fill_value=3 to the Series.add() method, we can fill null values or missing values in the Series.

Here, in this example, the Series.add() method fills the null values by the value 3 then it performs the addition. If the element in both the Series location has missing value and in the result, it will have the missing values. See the below example.

#importing pandas as pd
import pandas as pd
#creating Series
s_1= pd.Series([1,None,None])
s_2= pd.Series([4,5,None])
print("------After adding two series the result is------")
print(s_1.add(s_2,fill_value=3))


------After adding two series the result is------
0 5.0
1 8.0
2 NaN
dtype: float64

Conclusion

In this tutorial, we learned the Python pandas DataFrame.add() method. We learned syntax, parameters, and solved examples by applying this method on the DataFrame.