在numpy模块中,我们经常会使用resize 和 reshape,在具体使用中,通常是使用resize改变数组的尺寸大小,使用reshape用来增加数组的维度。
1.resize
之前看到别人的博客说,resize没有返回值,其实这取决于你如何使用resize,resize有两种使用方式,一种是没有返回值的,直接对原始的数据进行修改,还有一种用法是有返回值的,所以不会修改原有的数组值。
1.1有返回值,不对原始数据进行修改
import numpy as np
X=np.array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
X_new=np.resize(X,(3,3)) # do not change the original X
print("X:\n",X) #original X
print("X_new:\n",X_new) # new X
>>
X:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
X_new:
[[1 2 3]
[4 5 6]
[7 8 9]]
1.2 无返回值,直接修改原始数组的大小
import numpy as np
X=np.array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
X_2=X.resize((3,3)) #change the original X ,and do not return a value
print("X:\n",X) # change the original X
print("X_2:\n",X_2) # return None
X:
[[1 2 3]
[4 5 6]
[7 8 9]]
X_2:
None
2.reshape
给数组一个新的形状而不改变其数据
import numpy as np
X=np.array([1,2,3,4,5,6,7,8])
X_2=X.reshape((2,4)) #retuen a 2*4 2-dim array
X_3=X.reshape((2,2,2)) # retuen a 2*2*2 3-dim array
print("X:\n",X)
print("X_2:\n",X_2)
X[0]=666
print("X:\n",X)
print("X_2:\n",X_2)
输出为:
X:
[1 2 3 4 5 6 7 8]
X_2:
[[1 2 3 4]
[5 6 7 8]]
X:
[666 2 3 4 5 6 7 8]
X_2:
[[666 2 3 4]
[ 5 6 7 8]]
综上可知,
1. resize要么修改原数组为新格式,要么返回一份原数组的拷贝并修改为新格式,
2. 而 reshape既没有修改原数组,也没有返回拷贝,而是修改了数组的读取方式,并返回给变量,该变量后续读取都按这个格式来,即,可以理解为reshape返回了原数组的读取方式