How can I get an element-wise count of each element's number of occurrences in a numpy array, along a given axis? By "element-wise," I mean each value of the array should be converted to the number of times it appears.
Simple 2D input:
[[1, 1, 1],
[2, 2, 2],
[3, 4, 5]]
Should output:
[[3, 3, 3],
[3, 3, 3],
[1, 1, 1]]
The solution also needs to work relative to a given axis. For example, if my input array a
has shape (4, 2, 3, 3)
, which I think of as "a 4x2 matrix of 3x3 matrices," running solution(a)
should spit out a (4, 2, 3, 3)
solution of the form above, where each 3x3
"submatrix" contains counts of the corresponding elements relative to that submatrix alone, rather than the entire numpy array at large.
More complex example: suppose I take the example input above a
and call skimage.util.shape.view_as_windows(a, (2, 2))
. This gives me array b
of shape (2, 2, 2, 2)
:
[[[[1 1]
[2 2]]
[[1 1]
[2 2]]]
[[[2 2]
[3 4]]
[[2 2]
[4 5]]]]
Then solution(b)
should output:
[[[[2 2]
[2 2]]
[[2 2]
[2 2]]]
[[[2 2]
[1 1]]
[[2 2]
[1 1]]]]
So even though the value 1 occurs 3 times in a
and 4 times in b
, it only occurs twice in each 2x2
window.