【Python笔记】numpy reshape和resize的区别

主要两点区别。

区别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的区别(一清二楚)

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值