本文主要是介绍numpy reshape和resize的区别(一清二楚),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
主要两点区别。
区别一:
resize 无返回值(返回值为None),会改变原数组。
reshape 有返回值,返回值是被reshape后的数组,不会改变原数组。
import numpy as npA = 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 npA = 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的区别(一清二楚)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!