简体   繁体   中英

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.

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

Shape is a tuple, eg (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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM