能否请您解释一下3维数组切片?

时间:2020-08-23 20:02:57

标签: python numpy numpy-slicing

import numpy as np 

A = np.array(
    [ [ [45, 12, 4], [45, 13, 5], [46, 12, 6] ],
      [ [46, 14, 4], [45, 14, 5], [46, 11, 5] ],
      [ [47, 13, 2], [48, 15, 5], [52, 15, 1] ] ])
print(A[1:3, 0:2])

请对此进行解释。我一直在努力了解

2 个答案:

答案 0 :(得分:0)

以这种方式访问​​3D数组时,您的要求是切出这些数组的每个嵌套级别的一部分:

A[1:3, 0:2, 0:3]
# ↑↑↑
# Of the outer array (the outer []), take elements 1 (inclusive) to 3 (exclusive).
# Mind that counting starts at 0, so this is the second and third line in your example

A[1:3, 0:2, 0:3]
#      ↑↑↑
#      Out of the second level array, take the elements 0 (inclusive) to 2 (exclusive).
#      This is the first and the second group of three numbers each


A[1:3, 0:2, 0:3]
#           ↑↑↑
#           This you did not specify, but it is added automatically
#           Of the third level arrays, take element 0 (inclusive) to 3 (exclusive)
#           Those arrays only have 3 numbers each, so they are left untouched.


答案 1 :(得分:0)

In [483]: A = np.array( 
     ...:     [ [ [45, 12, 4], [45, 13, 5], [46, 12, 6] ], 
     ...:     [ [46, 14, 4], [45, 14, 5], [46, 11, 5] ], 
     ...:     [ [47, 13, 2], [48, 15, 5], [52, 15, 1] ] ])                                           

整个3d数组。如果需要在尺寸上加上名称,建议使用“ plane”,“ row”和“ column”:

In [484]: A                                                                                          
Out[484]: 
array([[[45, 12,  4],
        [45, 13,  5],
        [46, 12,  6]],

       [[46, 14,  4],
        [45, 14,  5],
        [46, 11,  5]],

       [[47, 13,  2],
        [48, 15,  5],
        [52, 15,  1]]])
In [485]: A.shape                                                                                    
Out[485]: (3, 3, 3)

在第一个维度(最后两个平面)上进行切片:

In [486]: A[1:3]                                                                                     
Out[486]: 
array([[[46, 14,  4],
        [45, 14,  5],
        [46, 11,  5]],

       [[47, 13,  2],
        [48, 15,  5],
        [52, 15,  1]]])

从每个平面取2行:

In [487]: A[1:3, 0:2]                                                                                
Out[487]: 
array([[[46, 14,  4],
        [45, 14,  5]],

       [[47, 13,  2],
        [48, 15,  5]]])

最后一个维度(列)是完整的,相当于A[1:3, 0:2, :](后切片是自动的)。

3D切片与1d和2d(以及4d等)相同。 3d没有什么特别之处或真正不同之处。