pythonnumpyindexingnumpy-ndarraynumpy-indexing

What is meant by indexing a numpy array with a conditional statement based on itself?


I'm working on a large library for network analysis and have come across a perplexing line whose calling convention I'm not familiar with.

    monitors = [1,2,3,4]
    nmonitors = 7 # This value is passed arbitrarily to the function

    while len(monitors) < nmonitors:
        remaining = np.arange(len(routers)) # len(routers) here is == 5
        for i in monitors:
            remaining = remaining[remaining != i]
        monitors.append(np.random.choice(remaining))

The line in questions in inside the loop which indexes the remaining array by a conditional based on i and itself. After some debugging it seems to be doing more than just evaluating a bool and indexing the array using that boolean value?

Would anyone be familiar with this syntax/convention and able to point me to the relevant part of numpy documentation or explain? I've been searching for hours with no results still, thank you.


Solution

  • There no special syntax, just a combination of generating a boolean array with a conditional test, and indexing an array with a boolean.

    A sample array:

    In [125]: arr = np.arange(4)
    In [126]: arr
    Out[126]: array([0, 1, 2, 3])
    

    Indexing with a boolean:

    In [127]: arr[[True,False,True,False]]
    Out[127]: array([0, 2])
    

    Creating a boolean with a test:

    In [128]: (arr%2)==0
    Out[128]: array([ True, False,  True, False])
    In [129]: arr[(arr%2)==0]
    Out[129]: array([0, 2])
    

    Or with a test like your example:

    In [131]: arr!=2
    Out[131]: array([ True,  True, False,  True])
    In [132]: arr[arr!=2]
    Out[132]: array([0, 1, 3])
    

    So that inner loop is removing all elements equal to monitors from remaining, leaving only [0]? The larger loop is buggy, but that has nothing to do with the "syntax" of the boolean indexing.