NumPy 数组重塑

NumPy 数组重塑仅仅意味着在不改变其数据的情况下改变数组的形状。

假设我们有一个一维数组。

np.array([1, 3, 5, 7, 2, 4, 6, 8])

我们可以将此一维数组重塑为 N 维数组,如下所示:

# reshape 1D into 2D array 
# with 2 rows and 4 columns
[[1 3 5 7]
 [2 4 6 8]]

# reshape 1D into 3D array 
# with 2 rows, 2 columns, and 2 layers
[[[1 3]
  [5 7]]

 [[2 4]
  [6 8]]]

在这里,我们可以看到一维数组已被重塑为二维和三维数组,而未更改其数据。


NumPy 数组重塑语法

NumPy 数组重塑的语法是:

np.reshape(array, newshape, order = 'C')

这里,

  • array - 需要重塑的输入数组,
  • newshape - 数组所需的形状
  • order (可选) - 指定数组元素的排列顺序。默认设置为 'C'

注意: order 参数可以接受三个值之一:'C''F''A'。我们将在本教程后面讨论它们。


在 NumPy 中将一维数组重塑为二维数组

我们使用 reshape() 函数将一维数组重塑为二维数组。例如:

import numpy as np

array1 = np.array([1, 3, 5, 7, 2, 4, 6, 8])

# reshape a 1D array into a 2D array 
# with 2 rows and 4 columns
result = np.reshape(array1, (2, 4))
print(result)

输出

[[1 3 5 7]
[2 4 6 8]]

在上面的示例中,我们使用 reshape() 函数将名为 array1 的一维数组的形状更改为二维数组。注意 reshape() 函数的使用:

np.reshape(array1, (2, 4))

这里,reshape() 接受两个参数:

  • array1 - 要重塑的数组
  • (2, 4) - array1 的新形状,指定为具有 **2** 行和 **4** 列的元组。

示例:在 NumPy 中将一维数组重塑为二维数组

import numpy as np

# reshape a 1D array into a 2D array 
# with 4 rows and 2 columns
array1 = np.array([1, 3, 5, 7, 2, 4, 6, 8])
result1 = np.reshape(array1, (4, 2))
print("With 4 rows and 2 columns: \n",result1)


# reshape a 1D array into a 2D array with a single row
result2 = np.reshape(array1, (1, 8))
print("\nWith a single row: \n",result2)

输出

With 4 rows and 2 columns: 
[[1 3]
 [5 7]
 [2 4]
 [6 8]]

With a single row: 
 [[1 3 5 7 2 4 6 8]]

注意:

  • 我们需要确保 reshape() 中的新形状与原始数组具有相同数量的元素,否则将引发 ValueError
  • 例如,将一个包含 **8** 个元素的**一维**数组重塑为具有 **2** 行和 **4** 列的**二维**数组是可能的,但将其重塑为具有 **3** 行和 **3** 列的**二维**数组则不可能,因为它需要 **3x3 = 9 个元素**。

在 NumPy 中将一维数组重塑为三维数组

在 NumPy 中,我们可以将一维 NumPy 数组重塑为具有指定行数、列数和层数的三维数组。例如:

import numpy as np

# create a 1D array
array1 = np.array([1, 3, 5, 7, 2, 4, 6, 8])

# reshape the 1D array to a 3D array
result = np.reshape(array1, (2, 2, 2))

# print the new array
print("1D to 3D Array: \n",result)

输出

1D to 3D Array: 
[[[1 3]
  [5 7]]

 [[2 4]
  [6 8]]]

这里,由于 array1 数组中有 **8** 个元素,np.reshape(array1, (2, 2, 2))array1 重塑为具有 **2** 行、**2** 列和 **2** 层的三维数组。


使用 reshape() 将 N 维数组展平为一维数组

展平数组仅仅是将多维数组转换为一维数组。

要将 N 维数组展平为一维数组,我们可以使用 reshape() 并将 **"-1"** 作为参数传递。

让我们看一个例子。

import numpy as np

# flatten 2D array to 1D
array1 = np.array([[1, 3], [5, 7], [9, 11]])
result1 = np.reshape(array1, -1)
print("Flattened 2D array:", result1)

# flatten 3D array to 1D
array2 = np.array([[[1, 3], [5, 7]], [[2, 4], [6, 8]]])
result2 = np.reshape(array2, -1)
print("Flattened 3D array:", result2)

输出

Flattened 2D array: [ 1  3  5  7  9 11]
Flattened 3D array: [1 3 5 7 2 4 6 8]

这里,reshape(array1, -1)reshape(array2, -1) 通过折叠所有维度将二维数组和三维数组转换为一维数组。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战