【问题标题】:Axis in a multidimensional NumPy array [duplicate]多维 NumPy 数组中的轴
【发布时间】:2014-08-08 11:54:09
【问题描述】:

我还没有理解 NumPy 中多维数组中轴之间的区别。你能给我解释一下吗? 特别是,我想知道 NumPy 三维数组中的axis0、axis1和axis2在哪里。 为什么?

【问题讨论】:

标签: python numpy


【解决方案1】:

最简单的方法是举个例子:

In [8]: x = np.array([[1, 2, 3], [4,5,6],[7,8,9]], np.int32)

In [9]: x
Out[9]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]], dtype=int32)

In [10]: x.sum(axis=0)  # sum the columns [1,4,7] = 12, [2,5,8] = 15 [3,6,9] = 18  
Out[10]: array([12, 15, 18])

In [11]: x.sum(axis=1)    # sum the rows [1,2,3] = 6, [4,5,6] = 15 [7,8,9] = 24
Out[11]: array([ 6, 15, 24])

轴 0轴 1

在一个三维数组中:

In [26]: x = np.array((((1,2), (3,4) ), ((5,6),(7,8))))
In [27]: x
Out[27]: 
   array([[[1, 2],
           [3, 4]],
          [[5, 6],
           [7, 8]]])
In [28]: x.shape # dimensions of the array
Out[28]: (2, 2, 2)

In [29]: x.sum(axis=0)
Out[29]: 
array([[ 6,  8],   #  [1,5] = 6 [2,6] = 8 [3,7] = 10 [4, 8] = 12
      [10, 12]])
In [31]: x.sum(axis=1)
Out[31]: 
    array([[ 4,  6],   # [1,3] = 4 [2,4] = 6 [5, 7] = 12 [6, 8] = 14
           [12, 14]])
In [33]: x.sum(axis=2) # [1, 2] = 3 [3, 4] = 7 [5, 6] = 11 [7, 8] = 15
Out[33]: 
array([[ 3,  7],
       [11, 15]])

In [77]: x.ndim # number of dimensions of the array
Out[77]: 3

Link 获取有关使用多维数据数组的好教程

【讨论】:

  • 所以我可以说axis0是命令“shape”的元组的第一个元素,axis1是第二个元素,axis2是第三个元素。对吗?
  • 是的。它是一个 2*2*2 数组。您可以使用x[0][0][1] 等访问特定元素。
  • "轴 0轴 1行。"或者换一种说法,我设法了解 numpy 轴的工作原理:“axis 0 是索引最大子数组的最外轴,而 axis n-1 是最内轴索引单个元素。
  • 或者换一种说法:x.sum(axis=0)x[sum][*][*]x.sum(axis=1)x[*][sum][*]x.sum(axis=2)x[*][*][sum]
【解决方案2】:

可以通过遍历 n 维数组来命名轴,从数组的外部到内部,直到我们到达实际的标量元素。 最外面的维度将始终是轴 0,而最里面的维度(标量元素)将是轴 n-1。 下面的链接在想象和实现 NumPy 轴时会更有用 - How does NumPy's transpose() method permute the axes of an array?

秘籍1:当你使用带有axis参数的NumPy sum函数时,你指定的轴就是被折叠的轴。

秘籍 2:当我们将轴参数与 np.concatenate() 函数一起使用时,轴参数定义了我们堆叠数组的轴。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 2020-10-02
    相关资源
    最近更新 更多