接上一文在构建三维函数时用到了reshape()函数,这里将对numpy中reshape函数的相关用法作出一些注释。
reshape()函数的功能
reshape()函数的功能是改变数组或矩阵的形状
a.reshape(m,n)表示将原有数组a转化为一个m行n列的新数组,a自身不变。m与n的乘积等于数组中的元素总数
reshape(m,n)中参数m或n其中一个可写为"-1","-1"的作用在于计算机根据原数组中的元素总数自动计算行或列的值。
1 2 | a = np.array(range(10), float) a |
1 | array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]) |
1 | a.reshape(5,-1) #将数组a改为一个5行的二维新数组,原数组a并未改变 |
1 2 3 4 5 | array([[0., 1.], [2., 3.], [4., 5.], [6., 7.], [8., 9.]]) |
1 | a #再次输出数组a,自身不变,依然是一维数组 |
1 | array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]) |
只有将a.reshape的值赋予a时,a才会发生改变
1 2 | a = a.reshape(-1, 2) #默认行优先 a |
1 2 3 4 5 | array([[0., 1.], [2., 3.], [4., 5.], [6., 7.], [8., 9.]]) |
此外在numpy中构建一个特定的元素连续的多维数组时,使用reshape函数更简单方便
例:直接创建
1 2 3 | a=np.array([0,1,2,3,4,5]) a=a+np.array([[[0],[6],[12],[18],[24],[30]]]) a |
使用fromfunction构建如上数组
1 2 3 4 | def f(x, y, z): return x+ 6*y+z a = np.fromfunction(f, (1, 6, 6,), dtype=int) a |
使用reshape()函数构建如上数组
1 | np.arange(36).reshape(1,6,6) |
输出结果都如下
1 2 3 4 5 6 | array([[[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35]]]) |
显而易见,reshape函数尤为简单。注意直接构建时三维数组的外面是一个()和两个[]
当然并不是reshape函数一定好,感兴趣的可以试着多构建几组数值不同的数组,对比reshape与fromfunction的优劣之处。比如
1 2 3 4 | def f(x, y, z): return x+ 10*y+z a = np.fromfunction(f, (1, 6, 6,), dtype=int) a |
输出结果
1 2 3 4 5 6 | array([[[ 0, 1, 2, 3, 4, 5], [10, 11, 12, 13, 14, 15], [20, 21, 22, 23, 24, 25], [30, 31, 32, 33, 34, 35], [40, 41, 42, 43, 44, 45], [50, 51, 52, 53, 54, 55]]]) |
这样的数组reshape则无法构建。因为reshepe构建数组的本质是改变np.arange()生成的一维数组的形状,而np.arange仅能创建一个等差序列的数组。
reshape()函数的默认排列方式
numpy中reshape()的默认排列方式是"按行"排列,即行优先,reshape(m,n)=reshape(m,n,order=‘c’);若要改为“按列”排列,可通过修改order参数进行改变,即reshape(m,n,order=‘f’)。
1 | a.reshape(5,-1,order='c') |
1 2 3 4 5 | array([[0., 1.], [2., 3.], [4., 5.], [6., 7.], [8., 9.]]) |
1 | a.reshape(5,-1,order='F') |
1 2 3 4 5 | array([[0., 5.], [1., 6.], [2., 7.], [3., 8.], [4., 9.]]) |
f(fortran)与c是两个语言,两个语言对数组的存储方式不同,fortran语言为列优先,c语言为行优先
reshape()函数默认的排列方式详细解释见https://blog.csdn.net/zhanggonglalala/article/details/79356653?ops_request_misc=%7B%22request%5Fid%22%3A%22160473361919195264735554%22%2C%22scm%22%3A%2220140713.130102334.pc%5Fblog.%22%7D&request_id=160473361919195264735554&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_v1~rank_blog_v1-1-79356653.pc_v1_rank_blog_v1&utm_term=numpy&spm=1018.2118.3001.4450