返回一個掩碼陣列,包含相同的資料,但形狀在NumPy中被視為行主序
要返回一個包含相同資料但具有新形狀的掩碼陣列,請在NumPy中使用**ma.MaskedArray.reshape()**方法。賦予陣列一個新形狀而不改變其資料。“**order**”引數設定順序。“C”順序決定陣列資料是否應按C語言(行主序)的方式檢視。
新形狀應該與原始形狀相容。如果提供一個整數,則結果將是一個具有該長度的一維陣列。
order引數決定陣列資料是按C語言(行主序)還是FORTRAN(列主序)順序檢視。返回一個包含相同資料但具有新形狀的掩碼陣列。結果是對原始陣列的檢視;如果無法實現,則會引發ValueError。
步驟
首先,匯入所需的庫:
import numpy as np import numpy.ma as ma
使用numpy.array()方法建立一個包含整數元素的陣列:
arr = np.array([[49, 85, 45], [67, 33, 59]])
print("Array...
", arr)
print("
Array type...
", arr.dtype)獲取陣列的維度:
print("Array Dimensions...
",arr.ndim)
建立一個掩碼陣列,並將其中一些標記為無效:
maskArr = ma.masked_array(arr, mask =[[0, 0, 1], [ 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("
Elements in the Masked Array...
",maskArr.size)
要返回一個包含相同資料但具有新形狀的掩碼陣列,請使用ma.MaskedArray.reshape()。順序由“order”引數設定。“C”順序決定陣列資料是否應按C語言(行主序)的方式檢視:
print("
Result...
",maskArr.reshape((6,1),order='C'))示例
# Python ma.MaskedArray - Return a masked array containing the same data but with a new shape
# viewed as row-major order
import numpy as np
import numpy.ma as ma
# Create an array with int elements using the numpy.array() method
arr = np.array([[78, 85, 51], [56, 33, 97]])
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
# The masked array is 1x6
maskArr = ma.masked_array(arr, mask =[[0, 1, 0, 0, 0, 1]])
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 return a masked array containing the same data, but with a new shape, use the ma.MaskedArray.reshape() method in Numpy
# Give a new shape to the array without changing its data
# The new shape of the masked array is set to 6x1 as a parameter
# The new shape should be compatible with the original shape.
# If an integer is supplied, then the result will be a 1-D array of that length
# The order is set using the "order" parameter
# The 'C' order determines whether the array data should be viewed as in C (row-major)
print("
Result...
",maskArr.reshape((6,1),order='C'))輸出
Array... [[78 85 51] [56 33 97]] Array type... int64 Array Dimensions... 2 Our Masked Array [[78 -- 51] [56 33 --]] Our Masked Array type... int64 Our Masked Array Dimensions... 2 Our Masked Array Shape... (2, 3) Elements in the Masked Array... 6 Result... [[78] [--] [51] [56] [33] [--]]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP