本教程和备忘单提供可视化帮助您了解numpy如何重塑多维数组。
Cheatsheet for Python numpy reshape, stack, and flatten (created by Hause Lin and available here)
numpy reshape()方法如何重整数组? 您是否感到困惑或难以理解其工作原理? 本教程将引导您逐步重塑numpy。 如果您需要上述备忘单的pdf副本,则可以在此处(https://github.com/hauselin/rtutorialsite/blob/master/_posts/2019-12-20-numpy-reshape/reshape.pdf)下载。
创建一个Python numpy数组
使用np.arange()生成一个numpy数组,其中包含从1到12的数字序列。请参见此处的文档。import numpy as npa1 = np.arange(1, 13) # numbers 1 to 12print(a1.shape)> (12,)print(a1)> [ 1 2 3 4 5 6 7 8 9 10 11 12]
使用reshape()方法重塑
使用reshape()方法将a1数组整形为3 x 4维数组。 让我们使用3_4来表示它的尺寸:3是第0个尺寸(轴),4是第1个尺寸(轴)(请注意,Python索引从0开始)。 请参阅此处的文档。a1_2d = a1.reshape(3, 4) # 3_4print(a1_2d.shape)> (3, 4)print(a1_2d)> [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]]
如果希望numpy自动确定特定尺寸应为多少尺寸/长度,请将该尺寸指定为-1。a1.reshape(3, 4)a1.reshape(-1, 4) # same as above: a1.reshape(3, 4)a1.reshape(3, 4)a1.reshape(3, -1) # s