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
>>> 

猜你喜欢

转载自blog.csdn.net/u010039418/article/details/81159906