Conditional Operations (where, extract) in NumPy

NumPy provides powerful functions like np.where() and np.extract() for performing conditional operations on arrays.

1. Importing NumPy

Before using conditional operations, import NumPy.

            import numpy as np
        

2. Using np.where()

The np.where() function returns indices where a condition is met or can be used for conditional element selection.

Finding Indices Where Condition is True

            arr = np.array([10, 20, 30, 40, 50])
            indices = np.where(arr > 25)
            print(indices)
            # Output: (array([2, 3, 4]),)
        

Using np.where() for Element Selection

It can also be used to replace values based on a condition.

            result = np.where(arr > 25, 1, 0)
            print(result)
            # Output: [0 0 1 1 1]
        

3. Using np.extract()

The np.extract() function directly returns elements that satisfy a condition.

            condition = arr > 25
            extracted_values = np.extract(condition, arr)
            print(extracted_values)
            # Output: [30 40 50]
        

4. Conclusion

NumPy's np.where() and np.extract() functions allow efficient conditional filtering and selection of elements in an array.





Advertisement