srkdb
srkdb

Reputation: 815

What does (n,) mean for a numpy array shape?

I'm starting out with Python and wondering why the size of an array is sometimes displayed as say (10,) instead of (10,1)? I'm also wondering if the difference affects any mathematical processing.

Upvotes: 2

Views: 1876

Answers (2)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

Shape is a tuple, e.g. (10, 1).

Pop quiz: How do we represent a one element tuple?

Does (10) work?

>>> type((10))
<class 'int'>

Nope. That's just a plain old int. Let's try (10,):

>>> type((10,))
<class 'tuple'>

There we go! That produces a tuple, as desired. So we should write (10,).


Try experimenting in your REPL.

>>> np.zeros((10,))
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

>>> np.zeros((10,)).shape
(10,)


>>> np.zeros((10, 1))
array([[0.],
       [0.],
       [0.],
       [0.],
       [0.],
       [0.],
       [0.],
       [0.],
       [0.],
       [0.]])

>>> np.zeros((10, 1)).shape
(10, 1)

Upvotes: 4

BarendB
BarendB

Reputation: 71

The difference between the two is whether you have a 1D array (10,) or a 2D array where one dimension is of size 1 (10,1).

Mathematical operations in numpy are quite robust. Although you might run into issues when broadcasting. For more details see: https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

Upvotes: 3

Related Questions