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]]]
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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.