This is my original 2d array A
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
[0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
[0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
[0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
[0, 2, 2, 8, 8, 8, 2, 0, 0, 0],
[0, 2, 2, 8, 8, 8, 2, 0, 0, 0],
[0, 0, 0, 8, 8, 8, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Let's say I want to return a 3x3 submatrix of 8's at the middle. I made a boolean mask with this expression A == 8 and it looks like this.
array([[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, True, True, True, False, False, False,
False],
[False, False, False, True, True, True, False, False, False,
False],
[False, False, False, True, True, True, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False]])
This is the point where I'm stuck. How can I return the submatrix with that boolean mask? If I do A[A == 8], it returns a flat array of 8s like this
array([8, 8, 8, 8, 8, 8, 8, 8, 8])
Another way is getting the row and column numbers with np.where(A == 8) which returns (array([5, 5, 5, 6, 6, 6, 7, 7, 7]), array([3, 4, 5, 3, 4, 5, 3, 4, 5])). How can I return the matrix using them?
Is there any better approach for this problem?
A[A==2]. Now if you are certain that8only appear in a block, you can detect the shape withargmin/argmax.