Table of Contents
TogglePandas Series is one of the primary data structures that stores the one-dimensional labeled data. The data can be any type, such as integers, floats, or strings. One of the primary advantages of using a Pandas Series is the ability to perform arithmetic operations in a vectorized manner. This means arithmetic operations on Series are performed without needing to loop through elements manually.
In this tutorial, we will learn how to apply arithmetic operations like addition (+), subtraction (-), multiplication (*), and division (/) to a single Series or between two Series objects.
Arithmetic operations on a Pandas Series object can be directly applied to all elements, meaning the operation is executed element-wise across all values. This is similar to how operations work with NumPy arrays.
| Operation | Example | Description |
|---|---|---|
| Addition | s + 2 | Adds 2 to each element |
| Subtraction | s - 2 | Subtracts 2 from each element |
| Multiplication | s * 2 | Multiplies each element by 2 |
| Division | s / 2 | Divides each element by 2 |
| Exponentiation | s ** 2 | Raises each element to the power of 2 |
| Modulus | s % 2 | Finds remainder when divided by 2 |
| Floor Division | s // 2 | Divides and floors the quotient |
import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
# Display the Input Series
print('Input Series\n',s)
# Apply all Arithmetic Operation and Display the Results
print('\nAddition:\n',s+2)
print('\nSubtraction:\n', s-2)
print('\nMultiplication:\n', s * 2)
print('\nDivision:\n', s/2)
print('\nExponentiation:\n', s**2)
print('\nModulus:\n', s%2)
print('\nFloor Division:\n', s//2)
You can perform arithmetic operations between two Series objects. Pandas automatically aligns the data by index labels. If one of the Series objects has an index not present in the other, the result for that index will be NaN.
import pandas as pd
s1 = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
s2 = pd.Series([9, 8, 6, 5], index=['x','a','b','c'])
# Apply all Arithmetic Operations and Display the Results
print('\nAddition:\n',s1+s2)
print('\nSubtraction:\n', s1-s2)
print('\nMultiplication:\n', s1 * s2)
print('\nDivision:\n', s1/s2)
