[Python] Numpy array boolean indexing to get containing element

Discussão em 'Python' iniciado por Stack, Janeiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    Given a (3,2,2) array how do I get second dimension elements given a single value on the third dimension

    import numpy as np


    arr = np.array([
    [[31., 1.], [41., 1.]],
    [[63., 1.],[73., 3.]],
    [[ 95., 1.], [100., 1]]
    ]
    )

    ref = arr[(arr[:,:,0] > 41.) & (arr[:,:,0] <= 63)]
    print(ref)


    Result

    [[63. 1.]]


    Expected result

    [[63., 1.],[73., 3.]]


    The input value is 63 so I don't know in advance 73 exists but I want to return it as well. In other words, if value exists return the whole parent array without reshaping.

    Another example

    ref = arr[(arr[:,:,0] <= 63)]

    Returns

    [[31. 1.]
    [41. 1.]
    [63. 1.]]


    But should return

    [[[31. 1.]
    [41. 1.]]
    [[63. 1.]
    [73. 1.]]]

    Continue reading...

Compartilhe esta Página