Simplicity
Simplicity

Reputation: 48986

What do we mean by this Numpy shape?

I came across this Python statement, but couldn't understand what it means, especially the part between parentheses:

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

I tried to mimic its behavior by a simple example, but got a tuple index out of range error.

Can you clarify what the parameters mean for the above array? An example would be very much appreciated.

Thanks.

Upvotes: 2

Views: 2492

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78564

Here's a toy code that can help you understand better

>>> 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.])

x.shape returns the shape of the array as a tuple (no of rows, no of columns) in this case (2, 3). x.shape[1] is therefore the number of the columns in the array. A new array filled with zeros (np.zeros(...)) is created using the given dimension: 1+3

Upvotes: 4

Abdul Fatir
Abdul Fatir

Reputation: 6357

It means: Create a 1D numpy array with zeros whose length is equal to one more than the number of columns in the numpy array x.

>>> 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 will have size equal to 1+(number of cols in a) = 1+3 = 4

Upvotes: 3

Related Questions