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]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP