Numpy MaskedArray.argsort()函数| Python
在许多情况下,数据集可能不完整或因存在无效数据而受到污染。例如,传感器可能无法记录数据,或记录无效值。 numpy.ma
模块通过引入掩码数组提供了解决此问题的便捷方法。掩码数组是可能缺少或无效条目的数组。
numpy.MaskedArray.argsort()
函数返回一个 ndarray 索引,该索引沿指定轴对数组进行排序。屏蔽值预先填充到 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.
代码#1:
# Python program explaining
# numpy.MaskedArray.argsort() method
# importing numpy as geek
# and numpy.ma module as ma
import numpy as geek
import numpy.ma as ma
# creating input array
in_arr = geek.array([4, 2, 3, -1, 5])
print ("Input array : ", in_arr)
# Now we are creating a masked array
# by making third entry as invalid.
mask_arr = ma.masked_array(in_arr, mask =[0, 0, 1, 0, 0])
print ("Masked array : ", mask_arr)
# applying MaskedArray.argsort methods to mask array
out_arr = mask_arr.argsort()
print ("output array of indices: ", out_arr)
Input array : [ 4 2 3 -1 5]
Masked array : [4 2 -- -1 5]
output array of indices: [3 1 0 4 2]
代码#2:
# Python program explaining
# numpy.MaskedArray.argsort() method
# importing numpy as geek
# and numpy.ma module as ma
import numpy as geek
import numpy.ma as ma
# creating input array
in_arr = geek.array([5, -5, 0, -10, 2])
print ("Input array : ", in_arr)
# Now we are creating a masked array
# by making first third entry as invalid.
mask_arr = ma.masked_array(in_arr, mask =[1, 0, 1, 0, 0])
print ("Masked array : ", mask_arr)
# applying MaskedArray.argminmethods to mask array
# and filling the masked location by 1
out_arr = mask_arr.argsort(fill_value = 1)
print ("output array of indices: ", out_arr)
Input array : [ 5 -5 0 -10 2]
Masked array : [-- -5 -- -10 2]
output array of indices: [3 1 0 2 4]