在 NumPy 中沿轴 1 对掩码数组进行就地排序
要对掩码数组进行就地排序,请在 NumPy 中使用 **ma.MaskedArray.sort()** 方法。axis 参数设置排序的轴。axis 值设置为 1。
该方法返回一个与数组类型和形状相同的数组。当数组是结构化数组时,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 值设置为 1:
maskArr.sort(axis = 1)
显示排序后的掩码数组:
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 1 maskArr.sort(axis = 1) # 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... [[59 77 -- --] [33 57 67 --] [29 51 88 --] [56 85 99 --]]
广告