Home > Software design >  Difference between numpy.shape() and X.shape
Difference between numpy.shape() and X.shape

Time:11-01

What is the difference between

np.shape(X[1])

and

X.shape[0]

where X is an array.

CodePudding user response:

array.shape and np.shape(array) are the same:

See on Numpy Docs

CodePudding user response:

np.shape is a function; x.shape is a property, that normally returns the same thing.

Make a sample array:

In [119]: x = np.ones((1,2,3),int)
In [120]: x
Out[120]: 
array([[[1, 1, 1],
        [1, 1, 1]]])
In [121]: x.shape
Out[121]: (1, 2, 3)          # a tuple
In [122]: x.shape[1]
Out[122]: 2                  # select the 2nd element of the tuple

The function returns the same tuple:

In [123]: np.shape(x)
Out[123]: (1, 2, 3)

Here x[0] is performed first, returning a new array:

In [124]: np.shape(x[0])
Out[124]: (2, 3)
In [125]: x[0].shape
Out[125]: (2, 3)

np.shape can take a non-array, such as a list of lists

In [126]: np.shape([[1],[2]])
Out[126]: (2, 1)

But if you want the 2nd dimension, you could use size, which returns just one number (depending on the optional axis parameter):

In [127]: np.size(x,1)
Out[127]: 2
In [128]: np.size(x)
Out[128]: 6
  • Related