Python 获取从索引到结尾的数组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13732025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:29:46  来源:igfitidea点击:

Get array elements from index to end

pythonvectornumpyindexing

提问by Edgar Andrés Margffoy Tuay

Suppose we have the following array:

假设我们有以下数组:

import numpy as np
a = np.arange(1, 10)
a = a.reshape(len(a), 1)
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

Now, i want to access the elements from index 4 to the end:

现在,我想访问从索引 4 到最后的元素:

a[3:-1]
array([[4],
       [5],
       [6],
       [7],
       [8]])

When i do this, the resulting vector is missing the last element, now there are five elements instead of six, why does it happen, and how can i get the last element without appending it?

当我这样做时,结果向量缺少最后一个元素,现在有五个元素而不是六个元素,为什么会发生这种情况,我如何在不附加它的情况下获取最后一个元素?

Expected output:

预期输出:

array([[4],
       [5],
       [6],
       [7],
       [8],
       [9]])

Thanks in advance

提前致谢

采纳答案by NPE

The [:-1]removes the last element. Instead of

[:-1]删除最后一个元素。代替

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

您可以在此处阅读 Python 切片符号:解释 Python 的切片符号

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

NumPy 切片是它的扩展。NumPy 教程有一些覆盖:索引、切片和迭代