Pum*_*n C 31 arrays numpy shape multidimensional-array numpy-ndarray
我有一个关于.shape函数的简单问题,这让我很困惑.
a = np.array([1, 2, 3]) # Create a rank 1 array
print(type(a)) # Prints "<class 'numpy.ndarray'>"
print(a.shape) # Prints "(3,)"
b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array
print(b.shape) # Prints "(2, 3)"
Run Code Online (Sandbox Code Playgroud)
.shape究竟做了什么?计算多少行,多少列,然后a.shape假设为,(1,3),一行三列,对吧?
kma*_*o23 47
yourarray.shape或np.shape()或np.ma.shape()返回你的ndarray的形状元组 ; 您可以使用yourarray.ndim或获取数组的尺寸np.ndim().
对于1D阵列,所述形状将是n其中ndarray是您的数组中的元素数目.
对于一个二维阵列,所述形状将是ndarray其中(n,)是行数和n是阵列中列的数量.
请注意,在一维的情况下,形状,简直是(n,m)什么,而不是你说,无论是n或m行和列向量分别.
这是遵循以下惯例:
对于1D数组,返回仅包含1个元素的形状元组(即)
对于2D数组,返回仅包含2个元素的形状元组(即)
对于3D数组,返回仅包含3个元素的形状元组(即)
对于4D数组,返回只有4个元素的形状元组(即)(n, )(1, n)(n, 1)(n,)
等等.
另外,请参阅下面的示例,了解1D数组和标量的行为(n,m)或(n,m,k)行为:
# sample array
In [10]: u = np.arange(10)
# get its shape
In [11]: np.shape(u) # u.shape
Out[11]: (10,)
# get array dimension using `np.ndim`
In [12]: np.ndim(u)
Out[12]: 1
In [13]: np.shape(np.mean(u))
Out[13]: () # empty tuple (to indicate that a scalar is a 0D array).
# check using `numpy.ndim`
In [14]: np.ndim(np.mean(u))
Out[14]: 0
Run Code Online (Sandbox Code Playgroud)
PS:因此,形状元组与我们对空间维度的理解是一致的,至少在数学上是这样.
与其最受欢迎的商业竞争对手不同,numpy 从一开始就几乎是关于“任意维”数组的,这就是核心类被称为ndarray. 您可以使用该.ndim属性检查 numpy 数组的维数。该.shape属性是一个.ndim包含每个维度长度的长度元组。目前,numpy 最多可以处理 32 个维度:
a = np.ones(32*(1,))
a
# array([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1.]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]])
a.shape
# (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
a.ndim
# 32
Run Code Online (Sandbox Code Playgroud)
如果一个 numpy 数组碰巧像你的第二个例子一样是 2d 的,那么从行和列的角度考虑它是合适的。但是 numpy 中的一维数组是真正的一维数组,没有行或列。
如果你想要像行或列向量这样的东西,你可以通过创建一个二维数组来实现,其中一个维度等于 1。
a = np.array([[1,2,3]]) # a 'row vector'
b = np.array([[1],[2],[3]]) # a 'column vector'
# or if you don't want to type so many brackets:
b = np.array([[1,2,3]]).T
Run Code Online (Sandbox Code Playgroud)