Boolean masks np, question 10 from practice set

Hey all,

My question relates to the above practice set.

Can someone please explain what .shape[1] is doing here?

mask = np.count_nonzero(x, axis=1) == x.shape[1]
rows_without_zeros = x[mask]

From what I understand, x.shape[1] required otherwise output would be an array, counting each row for number of non zeroes, i.e. in above, row 1 would be 4 (4 nonzeroes, 1 zero), row 2 = 4, row 3 = 5, row 4 = 5, row 5 = 4. (please correct me if i am wrong here)

is x.shape[1] returning it as boolean for the columns? why columns and not rows?

Thanks all

Hello @saturdaynightwrist

x.shape will give us the dimension of a NumPy array, ie, how many rows and columns do an array have.
It will return a tuple and the first value is the number of rows, the second value is the number of columns.

x.shape[1] is just indexing of getting the number of columns from array x.

From the code, you are trying to check if the number of non-zeros per row is the same as the number of columns of x. Therefore mask will be a boolean array, but x.shape[1] will have the number of columns in x, np.count_nonzero(x,axis=1) is the number of columns that have no zero per row in x.

Thanks for that explanation.

Actually, the second question is confusing me a little bit here:

the answer to the question is

mask = np.count_nonzero(x, axis=1) < x.shape[1]
rows_with_zeros = x[mask]

But I did this:

mask = np.count_nonzero(x, axis=1) == x.shape[1]
mask = mask == False 
rows_with_zeros = x[mask]

And it worked. Though I’m a bit worried that I still don’t understand this part:

mask = np.count_nonzero(x, axis=1) < x.shape[1]

Hello @saturdaynightwrist
The task was:

  1. Create a 1-dimensional array named rows_with_zeros that contains all rows of x that contain at least one zero.

There are various ways of arriving at the solution.

  1. Check whether the number of zeros is at least 1
  2. check whether the number of non-zeroes are not equal to the number of columns (this was your case)
  3. Check whether the number of non-zeroes are less than the number of columns (DQ’s solution)