Numpy recarray.compress () function | python

Arrays | NumPy | Python Methods and Functions

Record arrays allow you to access fields as elements of an array using arr.a and arr.b numpy.recarray.compress () returns the selected chunks of the array along the given axis.

Syntax: numpy.recarray.compress (condition, axis = None, out = None)

Parameters:
condition: [1-D array of bool] Array that selects which entries to return.
axis: [int, optional] Axis along which to take slices.
out: Results will be placed in this array.

Return: compressed_array, ndarray.

Code # 1:

# Python program explaining
# numpy.recarray.compress () method

  
# import numy as a geek

import numpy as geek

 
# create an input array with two different fields

in_arr = geek. array ([[( 5.0 , 2 ), ( 3.0 , - 4 ), ( 6.0 , 9 )], [( 9.0 , 1 ), ( 5.0 , 4 ), ( - 12.0 , - 7 )]],

dtype = [ ( `a` , float ), ( `b` , int )])

print ( "Input array:" , in_arr)

 
# convert it to an array of posts using arr.view (np.recarray)

rec_arr = in_ arr.view (geek.recarray)

print ( " Record array of int: " , rec_arr.b)

  
# using recarray.compress methods to place an array of posts

float_rec_arr = rec_arr.a

print ( " Record array of float: " , float_rec_arr)

out_arr = (rec_arr.a) .compress ([ 0 , 1 ], axis = 0 )

print ( "Output compressed array:" , out_arr) 

 
# applying recarray.compress methods to an array of int records

int_rec_arr = rec_arr.b 

print ( "Record array of int:" , int_rec_arr)

out_arr = int_rec_arr.compress ([ True , False ], axis = 1 )

print ( "Output compressed arr ay: " , out_arr) 

Output:

 Input array: [[(5.0, 2) (3.0, -4) (6.0, 9)] [(9.0, 1) (5.0, 4) (- 12.0, -7)]] Record array of int: [[2 -4 9] [1 4 -7]] Record array of float: [[5. 3. 6.] [9. 5. -12.]] Output compressed array: [[9. 5. -12.]] Record array of int: [[2 -4 9] [1 4 -7]] Output compressed array: [[2] [1]] 

Code # 2:

# Python program explaining
# numpy.recarray.compress () method

  
# import numy as geek

import numpy as geek

 
# create an input array with two different fields and

in_arr = geek.array ( [[( 5.0 , 2 ), ( 3.0 , - 4 ), ( 6.0 , 9 )], [( 9.0 , 1 ), ( 5.0 , 4 ), ( - 12.0 , - 7 )]],

  dtype = [( `a` , float ), ( ` b` , int )])

print ( "Input array:" , in_arr)

 
# convert it to an array of posts using arr.view ( np.recarray)

rec_arr = in_arr .view (geek.recarray)

print ( " Record array of int: " , rec_arr.b)

  
# applying meta recarray.compress codes to the entire array of records

out_arr = rec_arr.compress ([ True , False ], axis = 1 )

print ( "Output compressed array : " , out_arr) 

Output:

 Input array: [[(5.0, 2) (3.0, -4) (6.0, 9)] [(9.0, 1) (5.0, 4) (-12.0 , -7)]] Record array of int: [[2 -4 9] [1 4 -7]] Output compressed array: [[(5.0, 2)] [(9.0, 1)]] 




Get Solution for free from DataCamp guru