脾气暴躁:如果您事先不知道排名,则会在最后一个轴上编制索引 [英] Numpy: Indexing over the last axis when you don't know the rank in advance

查看:67
本文介绍了脾气暴躁:如果您事先不知道排名,则会在最后一个轴上编制索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我事先不知道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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆