What is the numpy.compress() Method

Numpy.compress() method “returns selected slices of an array along the mentioned axis that satisfies an axis.”

Syntax

numpy.compress (condition, input_array, axis = None, out = None)

Parameters

  1. 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.
  2. Input_array: It depicts the input array in which the user applies conditions on its elements
  3. axis: It Indicates which slice the user wants to select. It is optional, and by default, it works on a flattened array[1-D].
  4. out: It depicts the Output_array with elements of input_array, that satisfies the condition. It is an entirely optional parameter.

Return Value

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)[1], array, axis=0)
print("\nSliced array : \n", a)

Output

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)

Output

Original array : 
 [[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]

Sliced array : 
 [[0]
 [2]
 [4]
 [6]
 [8]]

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.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.