使用Numpy将输入转换为至少三维的数组
要将输入转换为至少三维的数组,请在Python Numpy中使用**ma.atleast_3d()**方法。参数是一个或多个类数组序列。非数组输入将转换为数组。已经具有三个或更多维度的数组将被保留。
该函数返回一个数组或数组列表,每个数组的a.ndim >= 3。尽可能避免复制,并返回具有三个或更多维度的视图。例如,形状为(N,)的一维数组将成为形状为(1, N, 1)的视图,形状为(M, N)的二维数组将成为形状为(M, N, 1)的视图。它应用于_data和_mask(如果存在)。
步骤
首先,导入所需的库:
import numpy as np import numpy.ma as ma
使用numpy.array()方法创建一个包含整数元素的数组:
arr = np.array([[65, 68, 81], [93, 33, 39], [73, 88, 51], [62, 45, 67]])
print("Array...
", arr)
print("
Array type...
", arr.dtype)获取数组的维度:
print("
Array Dimensions...
",arr.ndim)
创建一个掩码数组并将其中一些标记为无效:
maskArr = ma.masked_array(arr, mask =[[1, 1, 0], [ 1, 0, 0], [0, 1, 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("
Elements in the Masked Array...
",maskArr.size)
要将输入转换为至少三维的数组,请在Python Numpy中使用ma.atleast_3d()方法:
print("
Result...
",np.atleast_3d(1, maskArr))示例
import numpy as np
import numpy.ma as ma
# Create an array with int elements using the numpy.array() method
arr = np.array([[65, 68, 81], [93, 33, 39], [73, 88, 51], [62, 45, 67]])
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 =[[1, 1, 0], [ 1, 0, 0], [0, 1, 0], [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 convert inputs to arrays with at least three dimensions, use the ma.atleast_3d() method in Python Numpy
print("
Result...
",np.atleast_3d(1, maskArr))输出
Array... [[65 68 81] [93 33 39] [73 88 51] [62 45 67]] Array type... int64 Array Dimensions... 2 Our Masked Array [[-- -- 81] [-- 33 39] [73 -- 51] [62 -- 67]] Our Masked Array type... int64 Our Masked Array Dimensions... 2 Our Masked Array Shape... (4, 3) Elements in the Masked Array... 12 Result... [array([[[1]]]), masked_array( data=[[[--], [--], [81]], [[--], [33], [39]], [[73], [--], [51]], [[62], [--], [67]]], mask=[[[ True], [ True], [False]], [[ True], [False], [False]], [[False], [ True], [False]], [[False], [ True], [False]]], fill_value=999999)]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP