NumPy 数组中值的裁剪(限制)并将其结果放入另一个数组
要裁剪(限制)数组中的值,请在 Python NumPy 中使用 **np.ma.clip()** 方法。**“out”** 参数是结果将被放置在此数组中的位置。它可以是用于就地裁剪的输入数组。“out”必须具有正确的形状才能容纳输出。它的类型将被保留。给定一个区间,区间外的值将被裁剪到区间边缘。例如,如果指定 [0, 1] 的区间,则小于 0 的值将变为 0,大于 1 的值将变为 1。等效于但比 np.minimum(a_max, np.maximum(a, a_min)) 更快。
该函数返回一个包含 a 元素的数组,但是其中 < a_min 的值将被替换为 a_min,而 > a_max 的值将被替换为 a_max。
步骤
首先,导入所需的库:
import numpy as np
使用 numpy.array() 方法创建一个包含整数元素的数组:
arr = np.array([25, 32, 38, 47, 53, 66, 73, 79, 88, 95, 108]) print("Array...
", arr)
创建一个掩码数组并将其中一些标记为无效:
maskArr = ma.masked_array(arr, mask =[0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 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("
Number of elements in the Masked Array...
",maskArr.size)
要裁剪(限制)数组中的值,请在 Python NumPy 中使用 np.ma.clip() 方法。“out”参数是结果将被放置在此数组中的位置。它可以是用于就地裁剪的输入数组。“out”必须具有正确的形状才能容纳输出。它的类型将被保留:
print("
Result..
.",np.ma.clip(maskArr, 50, 80, out = maskArr)) print("
Result placed with out..
.",maskArr)
示例
import numpy as np import numpy.ma as ma # Create an array with int elements using the numpy.array() method arr = np.array([25, 32, 38, 47, 53, 66, 73, 79, 88, 95, 108]) print("Array...
", arr) # Create a masked array and mask some of them as invalid maskArr = ma.masked_array(arr, mask =[0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0]) print("
Our Masked Array...
", maskArr) # Get the type of the masked array 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("
Number of elements in the Masked Array...
",maskArr.size) # To clip (limit) the values in an array, use the np.ma.clip() method in Python Numpy # The "out" parameter is where results will be placed in this array. # It may be the input array for in-place clipping. out must be of the right shape to hold the output. # Its type is preserved. print("
Result..
.",np.ma.clip(maskArr, 50, 80, out = maskArr)) print("
Result placed with out..
.",maskArr)
输出
Array... [ 25 32 38 47 53 66 73 79 88 95 108] Our Masked Array... [25 -- 38 47 -- 66 73 79 88 -- 108] Our Masked Array type... int64 Our Masked Array Dimensions... 1 Our Masked Array Shape... (11,) Number of elements in the Masked Array... 11 Result.. . [50 -- 50 50 -- 66 73 79 80 -- 80] Result placed with out.. . [50 -- 50 50 -- 66 73 79 80 -- 80]
广告