在NumPy中沿轴1扩展数组的形状


要扩展数组的形状,可以使用 **numpy.expand_dims()** 方法。插入一个新数组,它将出现在扩展数组形状的轴位置。该函数返回具有增加的维度数量的输入数组的视图。

NumPy 提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等等。它支持广泛的硬件和计算平台,并且与分布式、GPU 和稀疏数组库良好兼容。

步骤

首先,导入所需的库:

import numpy as np

使用 array() 方法创建一个数组:

arr = np.array([5, 10, 15, 20, 25, 30])

显示数组:

print("Our Array...
",arr)

显示数组的形状:

print("
Array Shape...
",arr.shape)

检查维度:

print("
Dimensions of our Array...
",arr.ndim)

获取数据类型:

print("
Datatype of our Array object...
",arr.dtype)

获取数组中的元素个数:

print("
Size of array...
",arr.size)

要扩展数组的形状,可以使用 numpy.expand_dims() 方法:

res = np.expand_dims(arr, axis=1)

显示扩展后的数组:

print("
Resultant expanded array....
", res)

显示扩展后数组的形状:

print("
Shape of the expanded array...
",res.shape)

检查维度:

print("
Dimensions of our Array...
",res.ndim)

示例

import numpy as np

# Creating an array using the array() method
arr = np.array([5, 10, 15, 20, 25, 30])

# Display the array
print("Our Array...
",arr) # Display the shape of array print("
Array Shape...
",arr.shape) # Check the Dimensions print("
Dimensions of our Array...
",arr.ndim) # Get the Datatype print("
Datatype of our Array object...
",arr.dtype) # Get the number of elements in an array print("
Size of array...
",arr.size) # To expand the shape of an array, use the numpy.expand_dims() method # Insert a new axis that will appear at the axis position in the expanded array shape. res = np.expand_dims(arr, axis=1) # Display the expanded array print("
Resultant expanded array....
", res) # Display the shape of the expanded array print("
Shape of the expanded array...
",res.shape) # Check the Dimensions print("
Dimensions of our Array...
",res.ndim)

输出

Our Array...
[ 5 10 15 20 25 30]

Array Shape...
(6,)

Dimensions of our Array...
1

Datatype of our Array object...
int64

Size of array...
6

Resultant expanded array....
[[ 5]
[10]
[15]
[20]
[25]
[30]]

Shape of the expanded array...
(6, 1)

Dimensions of our Array...
2

更新于:2022年2月17日

3K+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告