Pandas Data Series: Add, subtract, multiple and divide two Pandas Series
Write a Pandas program to add, subtract, multiple and divide two Pandas Series.
Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 9]
Sample Solution :
Python Code :
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 9])
ds = ds1 + ds2
print("Add two Series:")
print(ds)
print("Subtract two Series:")
ds = ds1 - ds2
print(ds)
print("Multiply two Series:")
ds = ds1 * ds2
print(ds)
print("Divide Series1 by Series2:")
ds = ds1 / ds2
print(ds)
Sample Output:
Add two Series: 0 3 1 7 2 11 3 15 4 19 dtype: int64 Subtract two Series: 0 1 1 1 2 1 3 1 4 1 dtype: int64 Multiply two Series: 0 2 1 12 2 30 3 56 4 90 dtype: int64 Divide Series1 by Series2: 0 2.000000 1 1.333333 2 1.200000 3 1.142857 4 1.111111 dtype: float64
Explanation:
Following code creates two Pandas Series objects named 'ds1' and 'ds2' containing a sequence of five integers each:
ds1 = [2, 4, 6, 8, 10] ds2 = [1, 3, 5, 7, 9]
- ds = ds1 + ds2: This line adds the two Series objects element-wise, resulting in a new Series object 'ds' with the values [3, 7, 11, 15, 19].
- ds = ds1 - ds2: This line subtracts the second Series object from the first Series object element-wise, resulting in a new Series object 'ds' with the values [1, 1, 1, 1, 1].
- ds = ds1 * ds2: This line multiplies the two Series objects element-wise, resulting in a new Series object 'ds' with the values [2, 12, 30, 56, 90].
- ds = ds1 / ds2: This line divides the first Series object by the second Series object element-wise, resulting in a new Series object 'ds' with the values [2.0, 1.333, 1.2, 1.143, 1.111].
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Pandas program to convert a Panda module Series to Python list and it’s type.
Next: Write a Pandas program to compare the elements of the two Pandas Series.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics