AppDividend
Latest Code Tutorials

Python NumPy compress() Function Example

0

Python NumPy compress() is an inbuilt function that returns selected slices of an array along a given axis. The compress() function defined under NumPy, which can be imported as import NumPy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of NumPy, which is a library in Python.

When working along a given axis, a slice along that axis is returned in output for each index where condition evaluates to True. The above explanation works in case of the 2D array, and when working on a 1-D array, compress is equivalent to extract function.

Python NumPy compress()

Python NumPy compress() function returns the selected slices of an array along the given axis. When working along a given axis, a slice along that axis is returned in output for each index where condition evaluates to True.

Syntax

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

Parameters

  1. condition: It depicts the condition based on which user extract 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 entirely optional, and by default, it works on 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 array elements that are satisfied according to the given conditions along the given axis.

Examples

Write a program to show the working of the compress function.

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]]

Explanation

In the above code, according to the condition, elements in the row greater than 0 slices were returned along the 0 axis.

Code 2

See the following code.

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]]

Explanation

In the above code Boolean list was passed as a condition, so along the 1 axis, all the elements were extracted from the 1st column.

See also

Python NumPy empty()

Python NumPy ones()

Python NumPy zeros_like()

Python NumPy reshape()

Python NumPy ravel()

Leave A Reply

Your email address will not be published.

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