脾气暴躁:如果您事先不知道排名,则会在最后一个轴上编制索引 [英] Numpy: Indexing over the last axis when you don't know the rank in advance
问题描述
如果我事先不知道Numpy数组的排名,该如何索引它?
How can I index the last axis of a Numpy array if I don't know its rank in advance?
这是我想做的:让a
是一个未知排名的Numpy数组.我想要最后一个轴的最后一个k
元素的切片.
Here is what I want to do: Let a
be a Numpy array of unknown rank. I want the slice of the last k
elements of the last axis.
如果a
是一维,我想要
b = a[-k:]
如果a
是2D,我想要
b = a[:, -k:]
如果a
是3D,我想要
b = a[:, :, -k:]
以此类推.
我希望无论a
的等级如何(只要等级至少为1),它都能正常工作.
I want this to work regardless of the rank of a
(as long as the rank is at least 1).
我想要示例中最后一个k
元素的事实当然是无关紧要的,关键是,当我事先不知道数组的秩时,我想为最后一个轴指定索引
The fact that I want the last k
elements in the example is irrelevant of course, the point is that I want to specify indices for whatever the last axis is when I don't know the rank of an array in advance.
推荐答案
b = a[..., -k:]
文档.
这篇关于脾气暴躁:如果您事先不知道排名,则会在最后一个轴上编制索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!