简体   繁体   English

(n,) 对于 numpy 数组形状意味着什么?

[英]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)?我从 Python 开始,想知道为什么数组的大小有时显示为 (10,) 而不是 (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) .两者之间的区别在于您是否拥有一维数组(10,)或二维数组,其中一维的大小为 1 (10,1)

Mathematical operations in numpy are quite robust. numpy 中的数学运算非常健壮。 Although you might run into issues when broadcasting.尽管您在广播时可能会遇到问题。 For more details see: https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html有关更多详细信息,请参阅: https : //docs.scipy.org/doc/numpy/user/basics.broadcasting.html

Shape is a tuple, eg (10, 1) .形状是一个元组,例如(10, 1)

Pop quiz: How do we represent a one element tuple?小测验:我们如何表示一个单元素元组?

Does (10) work? (10)有效吗?

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

Nope.不。 That's just a plain old int .那只是一个普通的旧int Let's try (10,) :让我们试试(10,)

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

There we go!我们走了! That produces a tuple, as desired.根据需要生成一个元组。 So we should write (10,) .所以我们应该写(10,)


Try experimenting in your REPL.尝试在您的 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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