pythonnumpy

Does numpy implement indexed choice function


Here is an indexed choice function

def np_ifelse(
    x: np.ndarray[float] | float,
    ind: bool | np.ndarray[bool],
    v1: float,
    v2: float
) -> float | np.ndarray[float]:
    if isinstance(x, np.ndarray):
        y = np.full_like(x, v2)
        y[ind] = v1
        return y
    else:
        return v1 if ind else v2

In case the input is a scalar, it is a simple if-else statement between two possible outcomes, resulting in a scalar output

In case the input is an array, the if-else statement is applied individually to each array element, with the result being an array.

Question: This code looks somewhat ugly to me. Is there already a numpy function that does this more elegantly, without explicit type checking?


Solution

  • As the types of both x and ind are the same, you can skip checking the type of x and directly use ind with np.where:

    Example:

    import numpy as np
    
    # scalar input
    x_scalar = 5.0
    ind_scalar = True
    v1 = 10.0
    v2 = 20.0
    result_scalar = np.where(ind_scalar, v1, v2)
    print(result_scalar)
    
    # array input
    x_array = np.array([1.0, 2.0, 3.0, 4.0])
    ind_array = np.array([True, False, True, False])
    result_array = np.where(ind_array, v1, v2)
    print(result_array)
    

    Output:

    10.0
    [10. 20. 10. 20.]