Reshape,flatten,ravel data in NumPy is flattened, multidimensional arrays become one-dimensional arrays
import numpy as np
Using the Array object
arr1=np.arange(12).reshape(3,4)print(arr1)print(type(arr1))
[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]]<class ‘numpy.ndarray‘>
a=arr1.flatten() # 默认参数order=C,按照行进行展平;order=F,按照列进行展平,交叉展平;#A 或K参数用的不多,顾不变多记,到时候找到会用即可a[2]=1000print(arr1) # arr1 并没有改变,flatten 返回的是copya
[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]]array([ 0, 1, 1000, 3, 4, 5, 6, 7, 8, 9, 10, 11])
arr1=np.arange(12).reshape(3,4)b=arr1.reshape(-1) # b=arr1.reshape((-1)) 等同的效果意义 , b[2]=1000print(arr1)# 返回的是视图view
[[ 0 1 1000 3] [ 4 5 6 7] [ 8 9 10 11]]
arr1=np.arange(12).reshape(3,4)c=arr1.ravel()c
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
c[2]=10001arr1 # 返回的是视图view
array([[ 0, 1, 10001, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
arr1=np.arange(12).reshape(3,4)arr1.resize((4,3)) # 无返回值,即会对原始多维数组直接进行修改,也就是不能赋值arr1
array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]])
Working with a matrix object
# 使用matrix对象的时候,返回的仍是matrix,得不到想要的结果,不过该matrix仍然可以使用numpy中的一些方法对其操作,比如sum,min,max等等d=np.matrix(np.arange(12).reshape(3,4))d
matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
matrix([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])
Reshape,flatten,ravel data in NumPy is flattened, multidimensional arrays become one-dimensional arrays