0

I have a soduko board stored as blocks = np.full(81, fill_value=0 ).reshape((9,3,3))(Important note: blocks are indexed sequentially, but to take up less space I show them as a single 9x9 block instead of 9x3x3; middle block is index 4 (instead of (1,1), bottom left is index 6).
I want to count the amount of nonzero element in this per block, example:

[[0 0 0 0 0 0 0 0 0]
 [2 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 5 7 4 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]]

This has 1 nonzero in block 0 and 3 in block 4. I'm trying to use np.count_nonzero to achieve this, but the return value is never what I want no matter what axis I set as the parameter.
What I'd like to have as the output is a 9 long 1d array, but instead I get a (3,3) if I use count_nonzero along axis 0, a (9,3) along axes 1 and 2. While axis=2 does contain the value I want they are in different columns. Should I try to extract the values in a 1d array, or is there a way to make this work properly with count_nonzero?

Edit: Just to clarify blocks looks like this:

[[[0 0 0]
  [2 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]]

 [[5 7 4]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]]]

1 Answer 1

1

I think this is what you are trying to do if I understand your requirements correctly:

>>> z
array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
       [2, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 5, 7, 4, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0]])
>>> np.bincount(z.nonzero()[0], minlength=9)
array([0, 1, 0, 3, 0, 0, 0, 0, 0])
Sign up to request clarification or add additional context in comments.

5 Comments

it's very close, but instead of [1 0 0 0 3 0 0 0 0] this returns [0 1 0 3 0 0 0 0 0] for the example array
@devor yes, your example array is all zeros for the first row, hence the answer returns 0 nonzero items in the first position
Scrap my previous comment, it actually does work, my mistake was applying it to the 9x9 representation instead of the 9x(3x3)
@devor fair enough, glad it helped you out
Thanks for the help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.