移除 NumPy 中掩码数组中长度为一的轴
要移除 Python 中长度为一的轴,可以使用 NumPy 中的 **ma.MaskedArray.squeeze()** 方法。该方法返回输入数组,但移除所有或部分长度为 1 的维度。这始终是 a 本身或 a 的视图。请注意,如果所有轴都被压缩,则结果为 0 维数组而不是标量。
掩码数组是标准 numpy.ndarray 和掩码的组合。掩码要么是 nomask(表示关联数组中没有无效值),要么是布尔数组,用于确定关联数组的每个元素的值是否有效。
步骤
首先,导入所需的库:
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)
要移除长度为一的轴,请使用 NumPy 中的 ma.MaskedArray.squeeze() 方法:
print("
Result...
",np.squeeze(maskArr))
print("
Shape...
",np.squeeze(maskArr).shape)示例
# Python ma.MaskedArray - Remove axes of length one
import numpy as np
import numpy.ma as ma
# Create an array with int elements using the numpy.array() method
arr = np.array([[[15], [30], [45]]])
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
maskArr = ma.masked_array(arr, mask =[[0, 1, 0]])
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 remove axes of length one, use the ma.MaskedArray.squeeze() method in Numpy
print("
Result...
",np.squeeze(maskArr))
print("
Shape...
",np.squeeze(maskArr).shape)输出
Array... [[[15] [30] [45]]] Array type... int64 Array Dimensions... 3 Our Masked Array [[[15] [--] [45]]] Our Masked Array type... int64 Our Masked Array Dimensions... 3 Our Masked Array Shape... (1, 3, 1) Elements in the Masked Array... 3 Result... [15 -- 45] Shape... (3,)
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP