How to multiply pandas Series element wise?

In today’s tutorial we will learn how to calculate the multiplication of multiple pandas series objects as shown below.

series_3 = series_1 * series_2

Data Preparation

We will first import pandas and create two series of randomly created numbers:

import random
import pandas as pd

The create two random Series objects, each consisting of 20 elements.

s_employees= pd.Series(random.choices(range(30,100), k=20))
s_working_days = pd.Series(random.choices(range (20,30), k=20))

Expert Tip: When trying to generate random list, you might have used the random.sample() function. If so, you might have received the following error message:

# ValueError: Sample larger than population or is negative

If so, make sure to use the random.choices() function as shown above.

Multiplying you Series elements

We can now calculate the product of the two Series using the following vectorized operation

s_total_working_days = s_employees * s_working_days

Multiply by a constant / scalar / float

You are able to multiply your series by an integer scalar:

s_yearly_hours = s_total_working_days * 22

Similarly, you can multiply your pandas column by a float value:

s_yearly_hours = s_total_working_days * 22.545

Convert string series to numeric values and multiply

In case that you have a Series consisting of non numeric values, you won’t be able to apply arithmetic operations on it. Consider this example:

s1 = pd.Series([5,2,3,2,1])
s2 = pd.Series (["100", "200", "300", "400", "500"]) # series of strings


#we'll try to multiply the series objects:
s1*s2

This will render the following string series:

0    100100100100100
1             200200
2          300300300
3             400400
4                500
dtype: object

You can calculate the arithmetic multiplication by using the pandas pd.to_numeric() function:

s1*pd.to_numeric(s2)

This will render the right result

0    5000
1    4000
2    9000
3    8000
4    5000
dtype: int64

Sum your multiplied Series

After multiplying your two or more series you can easily sum the total:

print (f"The total number of working days was: {sum(s_total_working_days)}")

This will return the following string (your result will be different as we are using random data).

The total number of working days was: 31640

Follow up learning

How to create a chart from time Series data?