python ,numpy 模組中 resize 和 reshape的區別
阿新 • • 發佈:2018-12-29
在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) print("X_3:\n",X_3) >> X: [1 2 3 4 5 6 7 8] X_2: [[1 2 3 4] [5 6 7 8]] X_3: [[[1 2] [3 4]] [[5 6] [7 8]]]