python numpy的shape函数

shape函数是numpy.core.fromnumeric中的函数,它的作用就是获取矩阵或数组的维数,所谓维数也就是行和列的长度。shape的帮助信息如下,

Help on function shape in module numpy.core.fromnumeric:
shape(a)
    Return the shape of an array.
    Parameters
    ----------
    a : array_like
        Input array.

    Returns
    -------
    shape : tuple of ints
        The elements of the shape tuple give the lengths of the
        corresponding array dimensions.

看几个例子,

>>> a=eye(3)
>>> a
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
>>> a.shape
(3, 3)

对于一个3*3的单位矩阵,其维数就是(3,3),也就表示行长度为3,列长度为3。

对应的,a.shape[0]也就是矩阵的行长度,a.shape[1]是列长度。以一个4*2的矩阵为例,

>>> b=array([[1,2],[1,2],[1,2],[1,2]])
>>> b
array([[1, 2],
       [1, 2],
       [1, 2],
       [1, 2]])
>>> b.shape
(4, 2)
>>> b.shape[0]
4
>>> b.shape[1]
2
>>>

但是要注意的是对于一维数组,它只有行长度,没有列长度(并不是为1),

>>> c=array([2,2,3,4])
>>> c.shape
(4,)
>>> c.shape[0]
4
>>> c.shape[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值