Could you explain the code conataining shape to me?

task is: " Create a 1-dimensional array named cols_with_zeros that contains all columns of x that contain at least one zero."

Solution is:

import numpy as np
x = np.array([
    [6, 8, 90, 0, 4], 
    [8, 0, 5, 3, 10], 
    [2, 6, 10, 6, 6], 
    [10, 8, 3, 6, 7], 
    [10, 7, 7, 0, 2]
mask = np.count_nonzero(x, axis=0) < x.shape[0]
cols_with_zeros = x[:, mask]


Problem is: I don’t understand what <x.shape[0]does.

Have you tried playing around with x.shape to see what it produces? You can check out the documentation here.

Please note that because x is a square array (i.e. it has the same number of columns as it has rows) the expressions x.shape[0] and x.shape[1] will return the same value (specifically → 5).

Essentially the logic of constructing mask goes like this: “for each column, count how many nonzero values there are in each row and if it’s less than the total number of rows in x, return True, otherwise return False.” Ultimately this will produce a boolean array that indicates which columns contain 1 or more 0 values. For example, if mask returns [False, True, False, True, False] it means that the first, third, and fifth columns do not contain any 0 values but the second and fourth columns do contain 0 values.

Hope this helps and if it doesn’t, please let me know and we can try something else together.

1 Like