裁剪(限制)NumPy数组中的值
要裁剪(限制)数组中的值,请在Python NumPy中使用**np.ma.clip()**方法。给定一个区间,区间外的值将被裁剪到区间边缘。例如,如果指定[0, 1]区间,则小于0的值变为0,大于1的值变为1。等效于但比np.minimum(a_max, np.maximum(a, a_min))更快。
输出结果将放在此数组的out中。它可以是用于就地裁剪的输入数组。out必须具有正确的形状才能容纳输出。它的类型将被保留。
该函数返回一个包含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()方法:
print("
Result..
.", np.ma.clip(maskArr, 50, 80 ))
示例
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
print("
Result..
.", np.ma.clip(maskArr, 50, 80 ))输出
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]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP