Python numpy库 shape属性和reshape()方法

shape是数组array的属性;reshape()是数组array的方法

shape属性可以获得当前array的形状:

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7, 8])  # 一维数组
print(a.shape)  # 值为(8,)
print(a.shape[0])  # 值为8,因为有8个数据
# print(a.shape[1])  # IndexError: tuple index out of range

a = np.array([[1, 2, 3, 4],[5, 6, 7, 8]])  # 二维数组
print(a.shape)  # 值为(2, 4)
print(a.shape[0])  # 值为2,最外层矩阵有2个元素,2个元素还是矩阵。
print(a.shape[1])  # 值为4,内层矩阵有4个元素。
# print(a.shape[2])  # IndexError: tuple index out of range

y = np.zeros((2, 3, 4, 5))
print(y.shape)  # 值为(2, 3, 4, 5)
print(y)

y = np.zeros((2, 3, 4, 5))运行结果:

reshape()方法用于改变数组的形状(数组的形状会改变,但是数组中的值不会改变):

变成的新形状中所包含的元素个数必须符合原来元素个数。如果数组元素发生变化的时候,就会报错:

reshape()函数生成的新数组和原始数组公用一个内存,也就是说,不管是改变新数组还是原始数组的元素,另一个数组也会随之改变:

当不知道某一个维度值为多大时,可以使用-1:

-1只能使用一次,否则会报错(有多种输出可能):

参考:

  1. https://blog.csdn.net/qq_28618765/article/details/78083895
  2. https://blog.csdn.net/u010916338/article/details/84066369
  3. https://blog.csdn.net/m0_37592397/article/details/78695318
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值