{:check ["true"]}
#
# Import numpy as `np`, and set the display precision to two decimal places
#
import numpy as np
np.set_printoptions(precision=2)
#
# We generate three ndarrays to represent sales number of three products in four different seasons
#
np.random.seed(0)
sales = np.random.uniform(-20, 20, size=(4,3))
products = np.array(['apple', 'orange', 'banana'])
seasons = np.array(['spring', 'summer', 'fall', 'winter'])
#
# The products
#
products
#
# The seasons
#
seasons
#
# The sales as a (4,3) ndarray
sales
#
# We can also pack the seasons and products into a single
# (4,3) ndarray of strings.
#
info = np.array(
["%s-%s"%(s,p) for s in seasons for p in products]
).reshape(4,-1)
info
Boolean operations allows us to construct boolean ndarrays from numerical ndarrays using element-wise logical relational operators.
#
# sales that are negative
#
sales < 0
Logical operators can combine multiple boolean ndarrays to express complex conditions.
#
# sales that are between 0 and 2.0
#
np.logical_and(sales >= 0, sales < 2.0)
It's possible to find the indexes of all the true elements in a boolean ndarray. The result is given as indexes along each dimension.
X,Y = np.where(...)
X
is the row entries, and Y
is the column entries.
#
# the ndarray indices for negative sales
#
np.where(sales < 0)
We can make use of boolean arrays as indexes to extract the elements of a ndarray based on the corresponding boolean values.
#
# We can retrieve the actual sales figures for the negative sales
#
sales[sales < 0]
#
# We can retrieve the info of the negative sales
#
info[sales < 0]
I,J = np.where(sales < 0)
print(list(zip(I,J)))
seasons[I]
products[J]
L = (sales < 0)
I, J = np.where(L)
for (season, product, loss) in zip(seasons[I], products[J], sales[L]):
print("We lost %.2f selling %s in %s" % (loss, product, season))