在 Numpy 中扩展数组在元组轴上的形状


要扩展数组的形状,请使用 **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=(0, 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=(0, 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...
(2, 3)

Dimensions of our Array...
2

Datatype of our Array object...
int64

Size of array...
6

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

Shape of the expanded array...
(1, 1, 2, 3)

Dimensions of our Array...
4

更新于: 2022年2月18日

2K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告