Numpy array dimensions
我目前正在尝试学习numpy和python。给定以下数组:
1 2 | import numpy as np a = np.array([[1,2],[1,2]]) |
是否有返回
是
ndarray.shape
Tuple of array dimensions.
号
因此:
1 2 | >>> a.shape (2, 2) |
第一:
按照惯例,在python世界中,
1 2 3 | In [1]: import numpy as np In [2]: a = np.array([[1,2],[3,4]]) |
第二个:
在numpy中,尺寸、轴/轴、形状是相关的,有时是类似的概念:
维在数学/物理学中,尺寸或维数非正式地定义为指定空间内任何点所需的最小坐标数。但在numpy中,根据numpy文档,它与轴/轴相同:
In Numpy dimensions are called axes. The number of axes is rank.
号
1 2 | In [3]: a.ndim # num of dimensions/axes, *Mathematics definition of dimension* Out[3]: 2 |
。轴/轴
在numpy中索引
1 2 | 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) |
。形状
描述每个可用轴上有多少数据(或范围)。
1 2 | In [5]: a.shape Out[5]: (2, 2) # both the first and second axis have 2 (columns/rows/pages/blocks/...) data |
1 2 3 | import numpy as np >>> np.shape(a) (2,2) |
号
如果输入不是numpy数组,而是列表列表,也可以使用
1 2 3 | >>> a = [[1,2],[1,2]] >>> np.shape(a) (2,2) |
或者一个三元组
1 2 3 | >>> a = ((1,2),(1,2)) >>> np.shape(a) (2,2) |
。
你可以用.shape
1 2 3 4 5 6 7 | In: a = np.array([[1,2,3],[4,5,6]]) In: a.shape Out: (2, 3) In: a.shape[0] # x axis Out: 2 In: a.shape[1] # y axis Out: 3 |
你可以用
1 2 3 4 5 6 7 | var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]]) var.ndim # displays 2 var.shape # display 6, 2 |
。
您可以使用
1 2 3 4 5 6 7 | var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]]).reshape(3,4) var.ndim #display 2 var.shape #display 3, 4 |
号
1 | np.shape([[1,2],[1,2]]) |
。