Numpy MaskedArray.argsort() function | Python (original) (raw)

Last Updated : 27 Sep, 2019

In many circumstances, datasets can be incomplete or tainted by the presence of invalid data. For example, a sensor may have failed to record a data, or recorded an invalid value. The numpy.ma module provides a convenient way to address this issue, by introducing masked arrays.Masked arrays are arrays that may have missing or invalid entries.
numpy.MaskedArray.argsort() function return an ndarray of indices that sort the array along the specified axis. Masked values are filled beforehand 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 :

import numpy as geek

import numpy.ma as ma

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

print ( "Input array : " , in_arr)

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

print ( "Masked array : " , mask_arr)

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 :

import numpy as geek

import numpy.ma as ma

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

print ( "Input array : " , in_arr)

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

print ( "Masked array : " , mask_arr)

out_arr = mask_arr.argsort(fill_value = 1 )

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

Output:

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