shape和 reshape

补充: shape 属性
#参数是一个数时,返回空
>>> import numpy as np
>>> np.shape(0)
()
#参数是一维矩阵 返回的是一维数组的大小
>>> np.shape([1])
(1,)
>>> np.shape([1, 2])
(2,)
# 参数是二维矩阵
>>> np.shape([[1],[2]])
(2, 1)
>>> np.shape([[1, 2], [2, 3], [3, 4]])
(3, 2)

#直接用.shape可以快速读取矩阵的形状,使用shape[0]读取矩阵第一维度的长度
>>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> a.shape
(3, 3)
>>> a.shape[0]
3
>>> a.shape[1]
3
#但是当某一维度长度不一致时,读取所有维度时则不能读出长短不一致的维度
>>> a = np.array([[1, 2, 3], [4, 5], ])
>>> a.shape
>>> a.shape[0]
2
>>> a.shape[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
(2,)
补充: reshape函数
  • numpy.arange(n).reshape(a, b) 依次生成n个自然数,并且以a行b列的数组形式显示

    In [2]: np.arange(16).reshape(2,8)
    Out[2]: 
    array([[ 0,  1,  2,  3,  4,  5,  6,  7],
           [ 8,  9, 10, 11, 12, 13, 14, 15]])
    
  • reshape(-1)

In [4]: z.reshape(-1)
Out[4]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
  • reshape(-1, 1)

为了使列数变为1列,NumPy自动算出有16行

In [5]: z.reshape(-1,1)
Out[5]: 
array([[ 0],
       [ 1],
       [ 2],
       [ 3],
       [ 4],
       [ 5],
       [ 6],
       [ 7],
       [ 8],
       [ 9],
       [10],
       [11],
       [12],
       [13],
       [14],
       [15]])
  • reshape(-1, 2)

同理:reshape后的shape等于(8, 2)

z.reshape(-1,2)
Out[6]: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15]])
省略号应用
>>> x = numpy.arange(12).reshape(-1,4)
>>> x
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> x[...,1] # 第二列元素
array([1, 5, 9])
>>> x[1,...] # 第二行元素
array([4, 5, 6, 7])
>>> x[...,1:] # 第二列元素以及剩余元素
array([[ 1,  2,  3],
       [ 5,  6,  7],
       [ 9, 10, 11]])
>>> x[:2,...] # 第1,2行元素
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])

参考 :python 中 Numpy的应用 (shape,…)

参考 :Python中reshape函数参数-1的意思?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值