Numpy.compress() method “returns selected slices of an array along the mentioned axis that satisfies an axis.”
numpy.compress (condition, input_array, axis = None, out = None)
- condition: It depicts the condition based on which the user extracts elements. On applying a condition to the input_array, it returns an array filled with either True or False, and after those input_Array elements are extracted from the Indices having True value.
- Input_array: It depicts the input array in which the user applies conditions on its elements
- axis: It Indicates which slice the user wants to select. It is optional, and by default, it works on a flattened array[1-D].
- out: It depicts the Output_array with elements of input_array, that satisfies the condition. It is an entirely optional parameter.
The compress() function returns the copy of the array elements satisfied according to the given conditions along the axis.
Example 1: How does the np.compress() Method work?
import numpy as np array = np.arange(10).reshape(5, 2) print("Original array : \n", array) a = np.compress((array > 0), array, axis=0) print("\nSliced array : \n", a)
Original array : [[0 1] [2 3] [4 5] [6 7] [8 9]] Sliced array : [[0 1] [2 3]]
Example 2: How to Use np.compress() Method
import numpy as np array = np.arange(10).reshape(5, 2) print("Original array : \n", array) a = np.compress([True, False], array, axis=1) print("\nSliced array : \n", a)
Original array : [[0 1] [2 3] [4 5] [6 7] [8 9]] Sliced array : [    ]
In the above code, the Boolean list was passed as a condition, so along the 1 axis, all the elements were extracted from the 1st column.