主要两点区别。
区别一:
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)



本文详细介绍了numpy数组操作中resize和reshape的区别。resize会直接改变原数组的形状,可放大或缩小,多余或不足的元素通过0填充或直接丢弃。而reshape返回新数组,不改变原数组,且要求reshape前后元素总数相同。示例代码展示了resize和reshape的不同行为,强调了它们在元素数量不变条件下的应用。
9026





