numpy ndarray形状有什么作用? [英] what does numpy ndarray shape do?

查看:149
本文介绍了numpy ndarray形状有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对.shape函数有一个简单的问题,这使我很困惑.

I have a simple question about the .shape function, which confused me a lot.

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)"

.shape到底做了什么?计算多少行,多少列, 那么a.shape应该是(1,3),一行三列,对吧?

What did the .shape exactly do? count how many rows, how many columns, then the a.shape suppose to be, (1,3), one row three columns, right?

推荐答案

yourarray.ndim np.ndim(). (即,它给出了ndarrayn,因为NumPy中的所有数组都是n维数组(简称为ndarray s))

yourarray.shape or np.shape() or np.ma.shape() returns the shape of your ndarray as a tuple; And you can get the (number of) dimensions of your array using yourarray.ndim or np.ndim(). (i.e. it gives the n of the ndarray since all arrays in NumPy are just n-dimensional arrays (shortly called as ndarrays))

对于 1D 数组,形状为(n,),其中n是数组中元素的数量.

For a 1D array, the shape would be (n,) where n is the number of elements in your array.

对于 2D 数组,形状为(n,m),其中n是行数,而m是数组中的列数.

For a 2D array, the shape would be (n,m) where n is the number of rows and m is the number of columns in your array.

请注意,在 1D 情况下,形状将简单地为(n, ),而不是您分别将行向量和列向量表示为(1, n)(n, 1)的形状.

Please note that in 1D case, the shape would simply be (n, ) instead of what you said as either (1, n) or (n, 1) for row and column vectors respectively.

这是为了遵循以下约定:

This is to follow the convention that:

对于一维数组,返回仅包含 1 元素(即(n,))的 shape元组
对于2D数组,返回仅包含 2 个元素(即(n,m))
shape元组 对于3D数组,返回仅包含 3 个元素(即(n,m,k))
shape元组 对于4D数组,返回仅包含 4 个元素(即(n,m,k,j))

For 1D array, return a shape tuple with only 1 element (i.e. (n,))
For 2D array, return a shape tuple with only 2 elements (i.e. (n,m))
For 3D array, return a shape tuple with only 3 elements (i.e. (n,m,k))
For 4D array, return a shape tuple with only 4 elements (i.e. (n,m,k,j))

,依此类推.

此外,请参见下面的示例,以了解 np.shape()

Also, please see the example below to see how np.shape() or np.ma.shape() behaves with 1D arrays and scalars:

# 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

P.S.:因此,形状元组与我们对空间尺寸的理解(至少在数学上)一致.

P.S.: So, the shape tuple is consistent with our understanding of dimensions of space, at least mathematically.

这篇关于numpy ndarray形状有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆