NumPy reshape()

reshape() 方法在不改变数据的情况下更改 NumPy 数组的形状。

示例

import numpy as np

# create an array
originalArray = np.array([0, 1, 2, 3, 4, 5, 6, 7])

# reshape the array reshapedArray = np.reshape(originalArray, (2, 4))
print(reshapedArray) ''' Output [[0 1 2 3] [4 5 6 7]] '''

reshape() 语法

reshape() 的语法是:

numpy.reshape(array, shape, order)

reshape() 参数

reshape() 方法接受三个参数:

  • array - 要重塑的原始数组
  • shape - 数组所需的新形状(可以是整数或整数元组)
  • order (可选) - 指定重塑数组元素的顺序。

reshape() 返回值

reshape() 方法返回重塑后的数组。

注意: 如果形状与元素数量不匹配,reshape() 方法会引发错误。


示例 1:将 1D 数组重塑为 3D 数组

import numpy as np

# create an array
originalArray = np.array([0, 1, 2, 3, 4, 5, 6, 7])

# reshape the array to 3D reshapedArray = np.reshape(originalArray, (2, 2, 2))
print(reshapedArray)

输出

[[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]

在 reshape() 中使用可选的 Order 参数

order 参数指定重塑数组元素的顺序。

order 可以是:

  • 'C' - 元素按行存储
  • 'F' - 元素按列存储
  • 'A' - 元素根据原始数组的内存布局存储。

示例 2:按行重塑数组

import numpy as np

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

# reshape the array to 2D # the last argument 'C' reshapes the array row-wise reshapedArray = np.reshape(originalArray, (2, 4), 'C')
print(reshapedArray)

输出

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

示例 3:按列重塑数组

import numpy as np

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

# reshape the array to 2D # the last argument 'F' reshapes the array column-wise reshapedArray = np.reshape(originalArray, (2, 4), 'F')
print(reshapedArray)

输出

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

示例 4:将多维数组展平为 1D 数组

在之前的示例中,我们使用元组作为 shape 参数(第二个参数),它决定了新数组的形状。

但是,如果我们使用 -1 作为 shape 参数,reshape() 方法会将原始数组重塑为一维数组。

import numpy as np

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

# flatten the array # to flatten the array, -1 is used as the second argument reshapedArray = np.reshape(originalArray, -1)
print(reshapedArray)

输出

[0 1 2 3 4 5 6 7]

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

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

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