numpy中reshape方法详解

  reshape() 是 NumPy 中的一个函数,用于改变数组的形状(维度)。在不改变数组元素的情况下重新组织数组的维度。

reshape() 函数的语法如下:

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

参数说明:

  • array:要进行形状改变的数组。
  • newshape:表示新的形状的整数或整数元组。
  • order(可选):指定元素在新数组中的存储顺序。默认值是 ‘C’,表示按行存储(行主序)。其他可选值有 ‘F’,表示按列存储(列主序)和 ‘A’,表示保持原始数组的存储顺序。

  reshape() 函数返回一个具有新形状的数组,而不改变原始数组。如果新形状无法满足原始数组的元素数量,将引发一个错误。

import numpy as nparr = np.arange(12)# 创建一个包含 0 到 11 的一维数组print("原始数组:")print(arr)reshaped_arr = arr.reshape((3, 4))# 将一维数组转换为 3x4 的二维数组print("改变形状后的数组:")print(reshaped_arr)arr2 = np.arange(24).reshape((2, 3, 4))# 创建一个形状为 2x3x4 的三维数组print("三维数组:")print(arr2)flattened_arr = arr2.reshape(-1)# 将三维数组展平为一维数组print("展平后的数组:")print(flattened_arr)
原始数组:[ 0123456789 10 11]改变形状后的数组:[[ 0123] [ 4567] [ 89 10 11]]三维数组:[[[ 0123][ 4567][ 89 10 11]] [[12 13 14 15][16 17 18 19][20 21 22 23]]]展平后的数组:[ 0123456789 10 11 12 13 14 15 16 17 18 19 20 21 22 23]