mor*_*man 337 python arrays numpy dimensions
我目前正在尝试学习Numpy和Python.给出以下数组:
import numpy as np
a = np.array([[1,2],[1,2]])
Run Code Online (Sandbox Code Playgroud)
是否有一个返回维度的函数a(ega是一个2乘2的数组)?
size() 返回4,这没有多大帮助.
Fel*_*ing 461
它是.shape:
ndarray.shape
数组维度的元组.
从而:
>>> a.shape
(2, 2)
Run Code Online (Sandbox Code Playgroud)
YaO*_*OzI 59
按照惯例,在Python世界中,快捷方式numpy是np,所以:
In [1]: import numpy as np
In [2]: a = np.array([[1,2],[3,4]])
Run Code Online (Sandbox Code Playgroud)
在Numpy中,尺寸,轴/轴,形状是相关的,有时是相似的概念:
在数学/物理学中,维度或维度被非正式地定义为指定空间中任何点所需的最小坐标数.但在Numpy中,根据numpy doc,它与轴/轴相同:
在Numpy中,尺寸称为轴.轴数是等级.
In [3]: a.ndim # num of dimensions/axes, *Mathematics definition of dimension*
Out[3]: 2
Run Code Online (Sandbox Code Playgroud)
在Numpy中索引a 的第n个坐标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)
Run Code Online (Sandbox Code Playgroud)
描述沿每个可用轴的数据(或范围).
In [5]: a.shape
Out[5]: (2, 2) # both the first and second axis have 2 (columns/rows/pages/blocks/...) data
Run Code Online (Sandbox Code Playgroud)
use*_*975 44
import numpy as np
>>> np.shape(a)
(2,2)
Run Code Online (Sandbox Code Playgroud)
如果输入不是numpy数组而是列表列表,也可以工作
>>> a = [[1,2],[1,2]]
>>> np.shape(a)
(2,2)
Run Code Online (Sandbox Code Playgroud)
或元组元组
>>> a = ((1,2),(1,2))
>>> np.shape(a)
(2,2)
Run Code Online (Sandbox Code Playgroud)
小智 14
你可以使用.shape
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
Run Code Online (Sandbox Code Playgroud)
您可以使用.ndim维度并.shape了解确切的维度
var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]])
var.ndim
# displays 2
var.shape
# display 6, 2
Run Code Online (Sandbox Code Playgroud)
您可以使用.reshape功能更改尺寸
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
Run Code Online (Sandbox Code Playgroud)
该shape方法要求a是Numpy ndarray.但是Numpy也可以计算纯python对象的可迭代形状:
np.shape([[1,2],[1,2]])
Run Code Online (Sandbox Code Playgroud)