I have a numpy ndarray as below. I want to filter rows, cols where the fourth coordinate is not 1. i.e, where ndarary[0][0][-1] != 1
>>> print(ndarray)
array([[[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1],
...,
[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1]],
[[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1],
...,
[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1]],
[[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1],
...,
[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1]],
...,
[[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1],
...,
[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1]],
[[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1],
...,
[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1]],
[[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1],
...,
[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1]]], dtype=uint8)
Code I tried and which worked:
row_cols = []
for ir, row in enumerate(ndarray):
for ic, col in enumerate(row):
if col[-1] != 1:
row_cols.append((ir,ic))
But this is O(N^2) solution and highly time consuming, since the ndarray is of shape (800,1280*4) and I have to perform this on several thousands of arrays.
Is there a better way to filter?