本文主要是介绍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_likeInput array.Returns-------shape : tuple of intsThe elements of the shape tuple give the lengths of thecorresponding 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
>>>
这篇关于python numpy的shape函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!