在NumPy中沿轴0就地排序掩码数组
要就地排序掩码数组,请在Numpy中使用**ma.MaskedArray.sort()**方法。axis参数设置排序的轴。
该方法返回一个与数组类型和形状相同的数组。当数组是结构化数组时,order参数指定首先比较哪些字段,其次是哪些字段,依此类推。此列表不需要包含所有字段。
endwith参数建议是否应将缺失值(如有)视为最大值 (True) 或最小值 (False)。当数组包含在数据类型极值处排序的未掩码值时,这些值和掩码值的顺序是未定义的。fill_value是内部用于掩码值的数值。如果fill_value不为None,则它将取代endwith。
步骤
首先,导入所需的库:
import numpy as np import numpy.ma as ma
使用numpy.array()方法创建一个包含整数元素的数组:
arr = np.array([[55, 85, 59, 77], [67, 33, 39, 57], [29, 88, 51, 37], [56, 45, 99, 85]]) print("Array...
", arr) print("
Array type...
", arr.dtype)
获取数组的维度:
print("Array Dimensions...
",arr.ndim)
创建一个掩码数组,并将其中一些标记为无效:
maskArr = ma.masked_array(arr, mask =[[1, 1, 0, 0], [ 0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 0, 0]]) print("
Our Masked Array
", maskArr) print("
Our Masked Array type...
", maskArr.dtype)
获取掩码数组的维度:
print("
Our Masked Array Dimensions...
",maskArr.ndim)
获取掩码数组的形状:
print("
Our Masked Array Shape...
",maskArr.shape)
获取掩码数组的元素个数:
print("
Elements in the Masked Array...
",maskArr.size)
要就地排序掩码数组,请在Numpy中使用ma.MaskedArray.sort()方法。axis参数设置排序的轴。如果为None,则在排序前将数组展平。默认值为-1,沿最后一个轴排序。axis值设置为0:
maskArr.sort(axis = 0)
显示排序后的掩码数组:
print("
Sorted masked array...
",maskArr)
示例
import numpy as np import numpy.ma as ma # Create an array with int elements using the numpy.array() method arr = np.array([[55, 85, 59, 77], [67, 33, 39, 57], [29, 88, 51, 37], [56, 45, 99, 85]]) print("Array...
", arr) print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Create a masked array and mask some of them as invalid maskArr = ma.masked_array(arr, mask =[[1, 1, 0, 0], [ 0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 0, 0]]) print("
Our Masked Array
", maskArr) print("
Our Masked Array type...
", maskArr.dtype) # Get the dimensions of the Masked Array print("
Our Masked Array Dimensions...
",maskArr.ndim) # Get the shape of the Masked Array print("
Our Masked Array Shape...
",maskArr.shape) # Get the number of elements of the Masked Array print("
Elements in the Masked Array...
",maskArr.size) # To sort the masked array in-place, use the ma.MaskedArray.sort() method in Numpy # The axis parameter sets the axis along which to sort. # If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. # The axis value is set 0 maskArr.sort(axis = 0) # Display the Sorted Masked Array print("
Sorted masked array...
",maskArr)
输出
Array... [[55 85 59 77] [67 33 39 57] [29 88 51 37] [56 45 99 85]] Array type... int64 Array Dimensions... 2 Our Masked Array [[-- -- 59 77] [67 33 -- 57] [29 88 51 --] [56 -- 99 85]] Our Masked Array type... int64 Our Masked Array Dimensions... 2 Our Masked Array Shape... (4, 4) Elements in the Masked Array... 16 Sorted masked array... [[29 33 51 57] [56 88 59 77] [67 -- 99 85] [-- -- -- --]]
广告