numpy.expand_dims是numpy库中的一个函数,用于在指定位置插入一个新的维度。具体来说,它可以用来扩展数组的维度,将原来的数组包装在新的维度中。
该函数的语法如下:
numpy.expand_dims(arr, axis)
参数说明:
- arr:待扩展维度的数组。
- axis:新的维度将被插入的位置。axis的取值范围为[-(arr.ndim + 1), arr.ndim]。
返回值: 返回一个新的数组,该数组在指定位置插入了一个新的维度。
使用示例:
import numpy as np
a = np.array([1, 2, 3])
print(a.shape) # (3,)
b = np.expand_dims(a, axis=0)
print(b.shape) # (1, 3)
# 输出:[[1 2 3]]
c = np.expand_dims(a, axis=1)
print(c.shape) # (3, 1)
# 输出:[[1]
# [2]
# [3]]