What does .shape[] do in "for i in range(Y.shape[0])"?

HipsterCarlGoldstein picture HipsterCarlGoldstein · Apr 18, 2012 · Viewed 363.1k times · Source

I'm trying to break down a program line by line. Y is a matrix of data but I can't find any concrete data on what .shape[0] does exactly.

for i in range(Y.shape[0]):
    if Y[i] == -1:

This program uses numpy, scipy, matplotlib.pyplot, and cvxopt.

Answer

unutbu picture unutbu · Apr 18, 2012

The shape attribute for numpy arrays returns the dimensions of the array. If Y has n rows and m columns, then Y.shape is (n,m). So Y.shape[0] is n.

In [46]: Y = np.arange(12).reshape(3,4)

In [47]: Y
Out[47]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [48]: Y.shape
Out[48]: (3, 4)

In [49]: Y.shape[0]
Out[49]: 3