在 NumPy 中移除长度为一的轴(指定轴)
要移除长度为一的轴,可以使用 NumPy 中的 **ma.MaskedArray.squeeze()** 方法。轴可以通过 "axis" 参数设置。该轴选择形状中长度为一的条目子集。如果选择了一个形状条目大于一的轴,则会引发错误。
该函数返回输入数组,但移除了所有或一部分长度为 1 的维度。这始终是 a 本身或 a 的视图。请注意,如果所有轴都被压缩,则结果是一个 0 维数组,而不是一个标量。
步骤
首先,导入所需的库 -
import numpy as np import numpy.ma as ma
使用 numpy.array() 方法创建包含整数元素的数组 -
arr = np.array([[[15], [30], [45]]])
print("Array...
", arr)
print("
Array type...
", arr.dtype)获取数组的维度 -
print("
Array Dimensions...
",arr.ndim)
创建一个掩码数组,并将其中一些标记为无效 -
maskArr = ma.masked_array(arr, mask =[[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() 方法。轴可以通过 "axis" 参数设置 -
print("
Result...
",np.squeeze(maskArr, axis = 0))
print("
Shape...
",np.squeeze(maskArr, axis = 0).shape)示例
# Python ma.MaskedArray - Remove axes of length one with specific axis
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
# The axis is set using the "axis" parameter
print("
Result...
",np.squeeze(maskArr, axis = 0))
print("
Shape...
",np.squeeze(maskArr, axis = 0).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, 1)
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP