主要两点区别。
区别1:有无返回值,是否改变原数组
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)

区别2:变化前后元素个数的要求不同
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)


本文详细比较了numpy中的reshape和resize函数,主要关注它们的返回值、是否修改原数组、元素个数调整规则,并通过实例展示了两者的使用区别。
3万+

被折叠的 条评论
为什么被折叠?



