python - 切片 3d 数组
问题描述
我想以仅打印第二个数组中每一行的最后一个元素的方式对 3D 数组进行切片。
在我的 3D 阵列中:
np.random.seed(42)
M = np.random.randint(10, size=(2,2,10))
print(M)
我尝试以如下方式访问第二个数组的最后一个元素:
print(M[1::2]) ## which just prints me the whole 2nd Array
print(M[1::,2]) ## which gives me an error of index 2 being out of bounds
我理解第一个 print() 方法,例如:
1: # 选择第二个数组
: # 选择第二个数组的所有行
:2 # 选择行的每个第二个索引并打印它
奇怪的是,它打印了整个数组,这让我感到困惑。第二个 print() 方法我希望至少单独打印第二个索引,但我收到了该错误消息。
所以我尝试了更多并想出了那个代码:
print(M[1:,0:,::2])
它给了我想要的结果,但我无法阅读代码。我理解
1: ## 选择第二个数组
但是 ,0:,::2 让我感到困惑。::2 正在选择我猜的每个第二个索引,但我仍然不明白我什么时候可以制作 ':' 什么时候不能。或者切片过程中的“,”是什么意思。
解决方案
In numpy,the operator works as follows :- [start_index:end_index:step]
.
This means that when you index M[1:,0:,::2] what you are actually indexing is everything from the first index of the first dimension([1:]
), then everything from the start of the second dimension([0:]
), and finally every element with a step of 2 ([::2]
).
The ,
is used to seperate the dimensions so I assume what you actually want to do is M[:,1,-1]
to get the last element of every 2nd array.
推荐阅读
- python - Django在分页中保持相同的过滤器
- reactjs - React Hook "useEffect" 被有条件地调用,在所谓的简单的 get-display-retrieve 输入组件中
- masstransit - MassTransit 调度程序使用者不更新普罗米修斯指标
- xsd - 我可以从 Microsoft Graph 中的 openTypeExtension 获取结构 XSD 架构吗
- typescript - 设置 typescript 以使用 require 和 import 语法
- url - 您可以更改 Google Cloud Storage 上文件的公共 URL 吗?
- c# - 发送电子邮件时 D365 插件错误 0x80040265
- python - 为什么我在 python 中得到一个无效的语法错误?
- nginx - Nginx Tracing 无法进入上游服务
- spring-boot - Spring中的事务性kafka和数据库