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
Get array elements from index to end
提问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 教程有一些覆盖:索引、切片和迭代。

