numpy reshape和resize的区别(一清二楚)
·
主要两点区别。
区别一:
resize 无返回值(返回值为None),会改变原数组。
reshape 有返回值,返回值是被reshape后的数组,不会改变原数组。
import numpy as np
A = np.array([1, 2, 3, 4, 5, 6])
print("A:\n", A)
A_resize = A.resize((2, 3))
print("A_resize:\n", A_resize)
print("A(after resize):\n", A)
print('-'*10)
B = np.array([1, 2, 3, 4, 5, 6])
print("B:\n", B)
B_reshape = B.reshape((2, 3))
print("B_reshape:\n", B_reshape)
print("B(after reshape):\n", B)

区别二:
resize 可以放大或者缩小原数组的形状:放大时,会用0补全剩余元素;缩小时,直接丢弃多余元素。
reshape 要求reshape前后元素个数相同,否则会报错,无法运行。
import numpy as np
A = np.array([1, 2, 3, 4, 5, 6])
print("A:\n", A)
# 放大
A_resize = A.resize((3, 4))
print("A_resize:\n", A_resize)
print("A(after resize):\n", A)
# 缩小
A_resize = A.resize((2, 2))
print("A_resize:\n", A_resize)
print("A(after resize):\n", A)
print('-'*10)
B = np.array([1, 2, 3, 4, 5, 6])
print("B:\n", B)
B_reshape = B.reshape((3, 4)) # 这句会报错,reshape前后元素个数应当相同
print("B_reshape:\n", B_reshape)
print("B(after reshape):\n", B)


更多推荐


所有评论(0)