Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

x.shape[0] vs x[0].shape in NumPy

Let say, I have an array with

x.shape = (10,1024)

when I try to print x[0].shape

x[0].shape

it prints 1024

and when I print x.shape[0]

x.shape[0]

it prints 10

I know it's a silly question, and maybe there is another question like this, but can someone explain it to me ?

like image 297
Kevin Chandra Avatar asked Jan 07 '18 05:01

Kevin Chandra


1 Answers

x is a 2D array, which can also be looked upon as an array of 1D arrays, having 10 rows and 1024 columns. x[0] is the first 1D sub-array which has 1024 elements (there are 10 such 1D sub-arrays in x), and x[0].shape gives the shape of that sub-array, which happens to be a 1-tuple - (1024, ).

On the other hand, x.shape is a 2-tuple which represents the shape of x, which in this case is (10, 1024). x.shape[0] gives the first element in that tuple, which is 10.

Here's a demo with some smaller numbers, which should hopefully be easier to understand.

x = np.arange(36).reshape(-1, 9)
x

array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8],
       [ 9, 10, 11, 12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23, 24, 25, 26],
       [27, 28, 29, 30, 31, 32, 33, 34, 35]])

x[0]
array([0, 1, 2, 3, 4, 5, 6, 7, 8])

x[0].shape
(9,)

x.shape
(4, 9)

x.shape[0]
4
like image 108
cs95 Avatar answered Oct 17 '22 10:10

cs95