📜  在 NumPy 数组中插入一个新轴

📅  最后修改于: 2022-05-13 01:54:59.869000             🧑  作者: Mango

在 NumPy 数组中插入一个新轴

这篇文章介绍了在 NumPy 中增加数组维度的方法。 NumPy 为我们提供了两种不同的内置函数来增加数组的维数,即,

1D array will become 2D array
2D array will become 3D array
3D array will become 4D array
4D array will become 5D array

方法一:使用 numpy.newaxis()
第一种方法是使用 numpy.newaxis 对象。该对象相当于在声明数组时使用 None 作为参数。诀窍是在要添加新轴的索引位置使用 numpy.newaxis 对象作为参数。
例子:

Python3
import numpy as np
  
  
arr = np.arange(5*5).reshape(5, 5)
print(arr.shape)
  
# promoting 2D array to a 5D array
# arr[None, ..., None, None]
arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]
  
print(arr_5D.shape)


Python3
import numpy as np
  
  
x = np.zeros((3, 4))
y = np.expand_dims(x, axis=1).shape
print(y)


Python3
import numpy as np
  
  
arr = np.arange(5*5).reshape(5,5)
print(arr.shape)
  
newaxes = (0, 3, -1)
arr_5D = np.expand_dims(arr, axis=newaxes)
print(arr_5D.shape)


输出:

(5, 5)
(1, 5, 5, 1, 1)

方法 2:使用numpy.expand_dims()

第二种方法是使用具有直观轴 kwarg 的 numpy.expand_dims()函数。这个函数有两个参数。第一个是要增加其维度的数组,第二个是要在其上创建新轴的数组的索引/索引。
例子:

Python3

import numpy as np
  
  
x = np.zeros((3, 4))
y = np.expand_dims(x, axis=1).shape
print(y)

输出:

(3, 1, 4)

示例 2:在数组中同时插入许多新轴。

Python3

import numpy as np
  
  
arr = np.arange(5*5).reshape(5,5)
print(arr.shape)
  
newaxes = (0, 3, -1)
arr_5D = np.expand_dims(arr, axis=newaxes)
print(arr_5D.shape)

输出:

(5, 5)
(1, 5, 5, 1, 1)