0

Consider

x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])

In Python's view, x has shape (4, 3) and v shape (3, ). Why didn't Python view v as having shape (, 3). Also, why do v and v.T have the same shape (3, ). IMHO, I think if v has shape (3, ) then v.T should have shape (, 3)?

2
  • 2
    There are two issues - the proper notation for a tuple (shape is a tuple), and what does it mean to be 1 dimensional. People coming from MATLAB, and some linear algebra, backgrounds, can't conceive of an array that only has 1 dimension. It has to be a row vector or column vector, never a plain vector. :) Commented Mar 21, 2019 at 2:33
  • This does give it another dimension that I didn't think of. Thanks! Commented Mar 21, 2019 at 4:58

2 Answers 2

2

(3,) does not mean the 3 is first. It is simply the Python way of writing a 1-element tuple. If the shape were a list instead, it would be [3].

(, 3) is not valid Python. The syntax for a 1-element tuple is (element,).

The reason it can't be just (3) is that Python simply views the parentheses as a grouping construct, meaning (3) is interpreted as 3, an integer.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Tomothy. But why doesn't Python display the element of an array along with its dimension? I mean if it shows x.shape as (4, 3), it would be more intuitive/consistent to show v.shape as (1, 3) and v.T.shape as (3, 1)?
@Jason Because v is one dimensional, meaning len(v.shape) should be nothing else other than 1.
1

As you know, numpy arrays are n-dimensional. The shape tells dimensions in the order. If it is 1-D you will see only 1st dimension, 2-D only 2 dimensions and so on.

Here x is a 2-D array while v is a 1-D array (aka vector). That is why when you do shape on v you see (3,) meaning it has only one dimension whereas x.shape gives (4,3). When you transpose v, then that is also a 1-D array. To understand this better, try another example. Create a 3-D array.

z=np.ones((5,6,7))
z.shape
print (z)

3 Comments

Thanks, RebornCodeLover. I almost accepted your response as the answer but I wonder why Python's syntax doesn't allow the v.T.shape as (, 3) which both conform to v.T as one dimension and make distinction between v and v.T. Although Tomothy explained the syntax is (elements, ) but why can't it be (, elments)?
Whether it is v or v.T, it is exactly the same 1-D array. Try print(v) and print(v.T). But if you do on the 2-D array, you would see the rows and columns switched.
Yes I do realise that v and v.T are both 1-D. But my wish was that Python should have shape (3, ) and (, 3) respectively to make things more intuitive!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.