天天看点

最简单的方式讲明白numpy.reshape()函数

reshape() 函数: 这个方法是在不改变数据内容的情况下,改变一个数组的格式,参数如下图:

最简单的方式讲明白numpy.reshape()函数

参数说明:

a:输入的数组。

newshape:新格式数组的形状。

order:可选范围为{‘C’, ‘F’, ‘A’}。按照order的顺序读取a的元素,并按照索引顺序将元素放到变换后的的数组中。如果不进行order参数的设置,默认参数为C。

参数C:横着读,横着写,优先读/写一行。

参数F:竖着读,竖着写,优先读/写一列。

参数A:所生成的数组的效果与原数组a的数据存储方式有关,如果数据是按照FORTRAN

存储的话,它的生成效果与”F“相同,否则与“C”相同。

返回值:新生成的数组

举例1:将一维数组reshape成2×8的二维数组。

import numpy as np
 
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
a = np.asarray(a)
b = np.reshape(a, (2, 8))
print(b)
 
#或者这样写
 
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
 
a = np.asarray(a)
 
b = a.reshape((2, 8))
 
print(b)      

两种写法运行一样,运行结果:

[[ 0  1  2  3  4  5  6  7]

 [ 8  9 10 11 12 13 14 15]]

例2:将order设置为F。

import numpy as np
 
 
 
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
 
a = np.asarray(a)
 
b = np.reshape(a, (2, 8), order='f')
 
print(b)
 
c=np.reshape(b,(4,4),order='f')
 
print(c)