在numpy数组中获得第k个维度的第i个切片 [英] get the i-th slice of the k-th dimension in a numpy array
本文介绍了在numpy数组中获得第k个维度的第i个切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个n
维的numpy数组,我想获得第k
个维的第i
个切片.一定有比...更好的东西
I have an n
-dimensional numpy array, and I'd like to get the i
-th slice of the k
-th dimension. There must be something better than
# ...
elif k == 5:
b = a[:, :, :, :, :, i, ...]
# ...
推荐答案
b = a[(slice(None),) * k + (i,)]
手动构建索引元组.
Python语言参考中所述,表格
a[:, :, :, :, :, i]
转换为
a[(slice(None), slice(None), slice(None), slice(None), slice(None), i)]
我们可以直接构建该元组而不使用切片符号来达到相同的效果. (有一点需要注意的是,构建元组直接生成a[(i,)]
而不是k=0
的a[i]
,但是NumPy对于标量i
的处理相同.)
We can achieve the same effect by building that tuple directly instead of using slicing notation. (There's the minor caveat that building the tuple directly produces a[(i,)]
instead of a[i]
for k=0
, but NumPy handles these the same for scalar i
.)
这篇关于在numpy数组中获得第k个维度的第i个切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文