Numpy: Indexing over the last axis when you don't know the rank in advance

泪湿孤枕 提交于 2020-01-24 03:06:27

问题


How can I index the last axis of a Numpy array if I don't know its rank in advance?

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.

If a is 1D, I want

b = a[-k:]

If a is 2D, I want

b = a[:, -k:]

If a is 3D, I want

b = a[:, :, -k:]

and so on.

I want this to work regardless of the rank of a (as long as the rank is at least 1).

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.


回答1:


b = a[..., -k:]

This is mentioned in the docs.



来源:https://stackoverflow.com/questions/42916029/numpy-indexing-over-the-last-axis-when-you-dont-know-the-rank-in-advance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!