python - 在三维 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,但无法确定输出是打印为一维数组还是二维数组或更多。它是如何工作的?
输出:
解决方案
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]])
推荐阅读
- azure-devops - 由 PS 脚本导入的证书已损坏私钥
- php - 无法安装 ZMQ php 扩展。找不到 libzmq 安装。但它是通过“brew install zmq”安装的。MacOS 莫哈韦沙漠
- python - 运行不同版本的 Python 会出现“未找到”错误
- python - Plotly:如何在情节中包含多个文本变量?
- android - Android CheckBox 在恢复片段状态时不监听 OnCheckedChangeListener
- c# - Xamarin 表单:为什么 Popupimage 显示 2 次?
- php - 如何通过 laravel 在 JSON 数据库字段中存储具有 NULL 值的键?
- nsis - 使用 Nullsoft 安装应用程序时,如何在基于 32/64 位 windows 操作系统的目标文件夹中显示路径
- c# - 从组合框中动态添加 .EndsWith()
- select - 在jq中使用select和reduce?