首页 > 解决方案 > 在三维 numpy 数组中切片如何工作?

问题描述

import numpy as np
arr = np.array([[[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]]])
print(arr[0:2, : , 2] 

我知道选择了元素 3、6、9 和 12,但无法确定输出是打印为一维数组还是二维数组或更多。它是如何工作的?

输出:

在此处输入图像描述

标签: pythonpython-3.xnumpynumpy-slicing

解决方案


arr = np.array([[[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]]])

# array([[[ 1,  2,  3],
#         [ 4,  5,  6]],

#        [[ 7,  8,  9],
#         [10, 11, 12]]])

arr.shape # ------> (2,2,3)
# Think of them as axis
# lets create the first 2 axis of (`2`, ...)

#         |(1)
#         |
#         |
#         |         
#         |---------(0)


# now lets create second 2 axis of (2, `2`, ..)

#            (1,1)
#         |
#         |---(1,0)
#         |
#         |
#         |
#         |         |(0,1)
#         |---------|---(0,0)

# now lets create the last 3 axis of (2, 2, `3`)

#           /``(1,1,0) = 10
#          |-- (1,1,1) = 11
#         | \__(1,1,2) = 12
#         |
#         |  /``(1,0,0) = 7
#         |--|--(1,0,1) = 8
#         |  \__(1,0,2) = 9
#         |
#         |
#         |         /``(0,1,0) = 4
#         |         |--(0,1,1) = 5
#         |         \__(0,1,2) = 6
#         |         |
#         |         |
#         |---------|---/``(0,0,0) = 1
#                       |--(0,0,1) = 2
#                       \__(0,0,2) = 3

# now suppose you ask
arr[0, :, :] # give me the first axis alon with all it's component

#         |
#         |         /``(0,1,0) = 4
#         |         |--(0,1,1) = 5
#         |         \__(0,1,2) = 6
#         |         |
#         |         |
#         |---------|---/``(0,0,0) = 1
#                       |--(0,0,1) = 2
#                       \__(0,0,2) = 3

# So it will print 

# array([[1, 2, 3],
#        [4, 5, 6]])

arr[:, 0, :] # you ask take all the first axis 1ut give me only the first axis of the first axis and all its components

#           
#         
#         
#         
#         |  /``(1,0,0) = 7
#         |--|--(1,0,1) = 8
#         |  \__(1,0,2) = 9
#         |
#         |
#         |         
#         |         
#         |         
#         |         
#         |         
#         |---------|---/``(0,0,0) = 1
#                       |--(0,0,1) = 2
#                       \__(0,0,2) = 3

# so you get the output

# array([[1, 2, 3],
#        [7, 8, 9]])

# like wise you ask
print(arr[0:2, : , 2])
# so you are saying give (0,1) first axis, all of its children and only 3rd (index starts at 0 so 2 means 3) children
# 0:2 means 0 to 2 `excluding` 2; 0:5 means 0,1,2,3,4

#           
#          |
#         | \__(1,1,2) = 12
#         |
#         |  
#         |--
#         |  \__(1,0,2) = 9
#         |
#         |
#         |        
#         |         
#         |         \__(0,1,2) = 6
#         |         |
#         |         |
#         |---------|---/
#                       |
#                       \__(0,0,2) = 3

# so you get

# array([[ 3,  6],
#        [ 9, 12]])

推荐阅读