Numpy MaskedArray.argsort () Function | python



In many cases, datasets can be incomplete or corrupted due to the presence of incorrect data. For example, a sensor may not write data or write an invalid value. The numpy.ma module provides a convenient way to solve this problem by introducing masked arrays. Masked Arrays — these are arrays that can contain missing or invalid entries. 
numpy.MaskedArray.argsort() returns ndarray of indices that sort the array along the specified axis. Masked values ​​are pre-filled to fill_value.

Syntax: numpy.MaskedArray.argsort (axis = None, kind = `quicksort`, order = None, endwith = True, fill_value = None)

Parameters:
axis: [None, integer] Axis along which to sort … If None, the default, the flattened array is used.
kind: [`quicksort`, `mergesort`, `heapsort`] Sorting algorithm. Default is `quicksort`.
order: [list, optional] When a is an array with fields defined, this argument specifies which fields to compare first, second, etc.
endwith: [True, False, optional] Whether missing values ​​(if any) should be treated as the largest values ​​(True) or the smallest values ​​(False) When the array contains unmasked values ​​at the same extremes of the datatype, the ordering of these values ​​and the masked values ​​are undefined.
fill_value: [var, optional] Value used to fill in the masked values. If None, the output of minimum_fill_value (self._data) is used instead.

Return: [ndarray, int] Array of indices that sort a along the specified axis.

Code # 1:

# Python program explaining
# numpy.MaskedArray.argsort () method

 
# import numy as geek
# and numpy.ma module as ma

import numpy as geek

import numpy.ma as ma

 
# create input array

in_arr = geek.array ([ 4 , 2 , 3 , - 1 , 5 ])

print ( "Input array:" , in_arr)

 
# We now create a masked array
# invalidating the third entry.

mask_arr = ma.masked_array (in_arr, mask = [ 0 , 0 , 1 , 0 , 0 ])

print ( "Masked array:" , mask_arr)

 
# using MaskedArray.argsort methods to mask the array

out_arr = mask_arr.argsort ()

print ( " output array of indices: " , out_arr)

Output:

 Input array: [4 2 3 -1 5] Masked array: [4 2 - -1 5] output array of indices: [3 1 0 4 2] 

Code # 2:

# Python program explaining
# numpy.MaskedArray.argsort () method

 
# import numy as geek
# and numpy.ma module as ma

import numpy as geek

import numpy. ma as ma

 
# create input array

in_arr = geek.array ([ 5 , - 5 , 0 , - 10 , 2 ])

print ( "Input array:" , in_arr)

 
# Now we create a masked array
# making the first third entry invalid.

mask_arr = ma.masked_array (in_arr, mask = [ 1 , 0 , 1 , 0 , 0 ])

print ( "Masked array:" , mask_arr)

 
# using MaskedArray.argminmethods to mask the array
# and fill the masked space by 1

out_arr = mask_arr.argsort (fill_value = 1 )

print ( "output array of indices:" , out_arr)

Exit:

 Input array: [5 -5 0 -10 2] Masked array: [- -5 - -10 2] output array of indices: [3 1 0 2 4]