裁剪(限制)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