Numpy数组维度

2024-09-20 22:26:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在努力学习Numpy和Python。给定以下数组:

import numpy as np
a = np.array([[1,2],[1,2]])

是否有返回a维度的函数(例如a是一个2 x 2数组)?

size()返回4,这没有多大帮助。


Tags: 函数importnumpysizeasnp数组array
3条回答
import numpy as np   
>>> np.shape(a)
(2,2)

如果输入不是numpy数组,而是列表列表,也可以使用

>>> a = [[1,2],[1,2]]
>>> np.shape(a)
(2,2)

或者一对一对

>>> a = ((1,2),(1,2))
>>> np.shape(a)
(2,2)

它是^{}

ndarray.shape
Tuple of array dimensions.

因此:

>>> a.shape
(2, 2)

首先:

按照惯例,在Python世界中,numpy的快捷方式是np,因此:

In [1]: import numpy as np

In [2]: a = np.array([[1,2],[3,4]])

第二:

在Numpy中,维度轴/轴形状是相关的,有时是相似的概念:

尺寸

数学/物理中,维度或维度非正式地定义为指定空间内任何点所需的最小坐标数。但在Numpy中,根据numpy doc,它与轴/轴相同:

In Numpy dimensions are called axes. The number of axes is rank.

In [3]: a.ndim  # num of dimensions/axes, *Mathematics definition of dimension*
Out[3]: 2

轴/轴

在Numpy中,nth坐标表示一个array。多维数组每个轴可以有一个索引。

In [4]: a[1,0]  # to index `a`, we specific 1 at the first axis and 0 at the second axis.
Out[4]: 3  # which results in 3 (locate at the row 1 and column 0, 0-based index)

形状

描述每个可用轴上有多少数据(或范围)。

In [5]: a.shape
Out[5]: (2, 2)  # both the first and second axis have 2 (columns/rows/pages/blocks/...) data

相关问题 更多 >

    热门问题