使用stack()在轴0上连接一系列NumPy数组
要连接一系列数组,请在Python NumPy中使用**numpy.stack()**方法。axis参数指定结果维度中新轴的索引。如果axis=0,它将是第一维;如果axis=-1,它将是最后一维。
该函数返回的堆叠数组比输入数组多一个维度。axis参数指定结果维度中新轴的索引。例如,如果axis=0,它将是第一维;如果axis=-1,它将是最后一维。
如果提供out参数,则将其作为结果的存放目标。其形状必须正确,与未指定out参数时stack返回的形状匹配。
步骤
首先,导入所需的库:
import numpy as np
使用array()方法创建两个NumPy数组。我们插入了int类型的元素:
arr1 = np.array([49, 76, 61, 82, 69, 29]) arr2 = np.array([40, 60, 89, 55, 32, 98])
显示数组:
print("Array 1...
", arr1) print("
Array 2...
", arr2)
获取数组的类型:
print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)
获取数组的维度:
print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)
获取数组的形状:
print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)
要连接一系列数组,请在Python NumPy中使用numpy.stack()方法。axis参数指定结果维度中新轴的索引。如果axis=0,它将是第一维;如果axis=-1,它将是最后一维:
print("
Result (stack over axis 0)...
",np.stack((arr1, arr2), axis = 0))
示例
import numpy as np # Creating two numpy arrays using the array() method # We have inserted elements of int type arr1 = np.array([49, 76, 61, 82, 69, 29]) arr2 = np.array([40, 60, 89, 55, 32, 98]) # Display the arrays print("Array 1...
", arr1) print("
Array 2...
", arr2) # Get the type of the arrays print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype) # Get the dimensions of the Arrays print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim) # Get the shape of the Arrays print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape) # To join a sequence of arrays, use the numpy.stack() method in Python Numpy # The axis parameter specifies the index of the new axis in the dimensions of the result. # If axis=0 it will be the first dimension and if axis=-1 it will be the last dimension. print("
Result (stack over axis 0)...
",np.stack((arr1, arr2), axis = 0))
输出
Array 1... [49 76 61 82 69 29] Array 2... [40 60 89 55 32 98] Our Array 1 type... int64 Our Array 2 type... int64 Our Array 1 Dimensions... 1 Our Array 2 Dimensions... 1 Our Array 1 Shape... (6,) Our Array 2 Shape... (6,) Result (stack over axis 0)... [[49 76 61 82 69 29] [40 60 89 55 32 98]]
广告