这个Numpy形状是什么意思?

时间:2016-05-31 10:24:01

标签: python numpy

我遇到了这个Python声明,但无法理解它的含义,尤其是括号之间的部分:

np.zeros(1+x.shape[1])

我试图通过一个简单的例子来模仿它的行为,但是出现了tuple index out of range错误。

您能否澄清上述数组的参数含义?非常感谢一个例子。

感谢。

2 个答案:

答案 0 :(得分:4)

这是一个可以帮助您更好地理解的玩具代码

>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> x.shape
(2, 3)
>>> x.shape[1]
3
>>> np.zeros(1+x.shape[1])
array([ 0.,  0.,  0.,  0.])
在这种情况下,{p> x.shape将数组的形状作为元组(no of rows, no of columns)返回(2, 3)。因此x.shape[1]是数组中列的数量。使用给定维度创建一个填充零(np.zeros(...))的新数组:1+3

答案 1 :(得分:3)

这意味着:使用零创建一个numpy数组,其长度等于numpy数组>>> a = np.array([[1,2,1],[3,4,5]]) >>> print a.shape (2L, 3L) >>> b = np.zeros(1+a.shape[1]) >>> print b [ 0. 0. 0. 0.] 中的列数。

b

1+(number of cols in a)的大小等于1+3 = 4 = {{1}}