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 > S)
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
We merge these four lists into a two-dimensional array (the
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.