[Numpy * Operator] Element-wise Multiplication in Python

How does element-wise multiplication of two numpy arrays a and b work in Python’s Numpy library? Simply use the star operator “a * b”!

Here is a code example from my new NumPy book “Coffee Break NumPy”:

import numpy as np

# salary in ($1000) [2015, 2016, 2017]
dataScientist = [133, 132, 137]
productManager = [127, 140, 145]
designer = [118, 118, 127]
softwareEngineer = [129, 131, 137]

# Salary matrix
S = np.array([dataScientist,

# Salary increase matrix
I = np.array([[1.1, 1.2, 1.3],
[1.0, 1.0, 1.0],
[0.9, 0.8, 0.7],
[1.1, 1.1, 1.1]])

# Updated salary
S2 = S * I
print(S2[2][0] > S[2][0])

Can you guess the output of this puzzle?
*Advanced Level* (see solution below)

NumPy is a popular Python library for data science. Numpy focuses on array, vector, and matrix computations. If you work with data, you cannot avoid NumPy. So learn it now and learn it well.

We consider salary data of four jobs: data scientist, product manager, designer, and software engineer. We create four lists that store the yearly average salary of the four jobs in thousand dollars for three subsequent years.
We merge these four lists into a two-dimensional array (the matrix). You can think of it as a list of lists, or as a table. Each salary list of a single job becomes a row of this matrix. Each row has three columns, one for each year.

Now suppose, your company changes the salary for the different job descriptions. For example, data scientists get a salary raise of 30% in 2017.

In the puzzle, we create a second matrix that stores the salary changes as weights. Then, we update the salaries according to these weights. As designers in 2015 got a salary decrease, i.e., the weight is smaller than 1.0, the new salary is smaller than the old salary.

Note that the simple multiplication operator ‘*’ creates a new matrix by multiplying the two values at position (i,j) of the two matrices.

Are you a master coder?
Test your NumPy skills now by solving this code puzzle!

Where to go from here?

This puzzle is loosely based on my new book “Coffee Break NumPy”. My idea in writing the “Coffee Break” series is to deliver continuous improvements in Python — while not taking more time than your daily coffee break.

Related Video



Leave a Comment

Your email address will not be published. Required fields are marked *