Home > OS >  Extract rows with 0 element from a list of numpy arrays?
Extract rows with 0 element from a list of numpy arrays?

Time:10-20

Here is the bunch of points that I would like to extract only the rows with 0 being the 1st element or the column value of 0. This is the output snippet of the list.

array([[ 29.42787794, 453.        , 496.        ],
        [  **0.**        , **424.        , 491.**        ],
        [ 34.66987165, 453.        , 472.        ],
        [ 26.        , 414.        , 467.        ],
        [ 48.27007354, 393.        , 454.        ],
        [ 51.4781507 , 417.        , 440.        ]]),
 array([[ 24.        , 453.        , 496.        ],
        [ 34.66987165, 424.        , 491.        ],
        [  **0.**        , **453.        , 472.**        ],
        [ 39.3192065 , 414.        , 467.        ],
        [ 28.        , 453.        , 444.        ],
        [ 48.16637832, 417.        , 440.        ],
        [ 48.70318265, 469.        , 426.        ]]),
 array([[ 48.60041152, 453.        , 496.        ],
        [ 26.        , 424.        , 491.        ],
        [ 39.3192065 , 453.        , 472.        ],
        [  **0.        , **414.        , 467.****        ],
        [ 24.69817807, 393.        , 454.        ],
        [ 45.27692569, 453.        , 444.        ],
        [ 27.16615541, 417.        , 440.        ],
        [ 42.19004622, 392.        , 431.        ],
        [ 51.623638  , 433.        , 419.        ]])

So I want to extract the bolded points from this list of arrays. I am unsure on how to do it? I have tried numpy.where, np.any before appending the arrays into the list but nothing really seems to work. Moving forward I would like to know if its possible to use a list to get the bold points. The len(list) is the number the appended arrays together. So I am kinda confused on how can I go about retrieving just singular points from the separate arrays in a list.

CodePudding user response:

Do you mean by:

>>> arr = np.vstack(arr)
>>> arr[arr[:, 0] == 0]
array([[  0., 424., 491.],
       [  0., 453., 472.],
       [  0., 414., 467.]])
>>> 

Or you try np.isclose:

>>> arr = np.vstack(arr)
>>> arr[np.isclose(0, arr[:, 0])]
array([[  0., 424., 491.],
       [  0., 453., 472.],
       [  0., 414., 467.]])
>>> 

CodePudding user response:

One approach is to np.isclose to detect the rows where the first element is close to zero:

res = [arr[np.isclose(0, arr[: ,0])] for arr in lst]
print(res)

Output

[array([[  0., 424., 491.]]), array([[  0., 453., 472.]]), array([[  0., 414., 467.]])]
  • Related