Introduction
In this lab, we will learn how to use the add() method in Pandas to perform addition on a Series. The add() method allows us to add a Series with another Series or with a scalar value. We can also fill in missing or null values using the fill_value parameter.
VM Tips
After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.
Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.
If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.
Create a Series
Let's start by importing the pandas library and creating a Series.
import pandas as pd
## Create a Series
s = pd.Series([1, 2, 3, 4])
print("Original Series:")
print(s)
Output:
Original Series:
0 1
1 2
2 3
3 4
dtype: int64
Add a Scalar Value to the Series
We can use the add() method to add a scalar value to each element in the Series. In this example, we will add the scalar value 2 to each element in the Series.
print("\nSeries after adding a scalar value:")
print(s.add(2))
Output:
Series after adding a scalar value:
0 3
1 4
2 5
3 6
dtype: int64
Add Two Series
We can also use the add() method to add two Series together. In this example, we will create two Series s1 and s2 and add them together.
## Create two Series
s1 = pd.Series([1, 2, 3])
s2 = pd.Series([4, 5, 6])
print("\nResult of adding two Series:")
print(s1.add(s2))
Output:
Result of adding two Series:
0 5
1 7
2 9
dtype: int64
Fill Missing Values
The add() method also supports filling in missing or null values. We can use the fill_value parameter to specify a value to fill in the missing values before performing the addition. In this example, we will create two Series s1 and s2 with missing values and fill them with the value 3 before adding them together.
## Create two Series with missing values
s1 = pd.Series([1, None, None])
s2 = pd.Series([4, 5, None])
print("\nResult of adding two Series with missing values:")
print(s1.add(s2, fill_value=3))
Output:
Result of adding two Series with missing values:
0 5.0
1 8.0
2 NaN
dtype: float64
Summary
In this lab, we learned how to use the add() method in Pandas to perform addition on a Series. We can add a scalar value to each element in a Series, add two Series together, and fill in missing or null values. The add() method is a useful tool for performing element-wise addition on Series in Pandas.