首页 文章

Numpy数组维度

提问于
浏览
296

我目前正在尝试学习Numpy和Python . 给出以下数组:

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

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

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

6 回答

  • 406

    它是.shape

    ndarray.shape数组维度的元组 .

    从而:

    >>> a.shape
    (2, 2)
    
  • 42

    shape 方法要求 a 是Numpy ndarray . 但Numpy还可以计算纯python对象的可迭代形状:

    np.shape([[1,2],[1,2]])
    
  • 10

    你可以使用.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
    
  • 6

    您可以使用 .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
    

    您可以使用 .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
    
  • 44

    第一名:

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

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

    第二名:

    在Numpy中, dimensionaxis/axesshape 是相关的,有时是类似的概念:

    维度

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

    在Numpy维度中称为轴 . 轴数是等级 .

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

    轴/轴

    在Numpy中索引 array 的第n个坐标 . 多维数组每个轴可以有一个索引 .

    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
    
  • 4
    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)
    

相关问题