Search code examples
pythonnumpysyntax

numpy array slicing and masking


I've come across numpy syntax I don't entirely understand. Here it is:

array[:, mask] = a

array is a numpy array of indeces, mask is a numpy array of bool values and a is an integer.

Could someone please translate this notation for me?

I couldn't find the answer anywhere online.


Solution

  • Translation:

    • in the array array
    • for the rows [:] (all in this case)
    • do for every column where mask contains True
    • the operation: assign a

    So it writes a into all matrix cells there masks contains a True value.

    here is an example:

    import numpy as np
    
    array = np.array([
        [1,5,3],
        [1,5,3],
        [1,5,3],
    ])
    mask = np.array(
        [True,False,True]
    )
    array[:, mask] = 10
    print(array)
    

    results in:

    [[10  5 10]
     [10  5 10]
     [10  5 10]]