简体   繁体   English

从开始到结束的Numpy切片

[英]Numpy slice from beginning and from end

array = numpy.array([1,2,3,4,5,6,7,8,9,10])
array[-1:3:1]
>> []

I want this array indexing to return something like this: 我希望这个数组索引返回这样的东西:

[10,1,2,3]

Use np.roll to: 使用np.roll来:

Roll array elements along a given axis. 沿给定轴滚动数组元素。 Elements that roll beyond the last position are re-introduced at the first. 超出最后位置的元素将在第一个位置重新引入。

>>> np.roll(x, 1)[:4]
array([10,  1,  2,  3])

np.roll lets you wrap an array which might be useful np.roll允许你包装一个可能有用的数组

import numpy as np

a = np.array([1,2,3,4,5,6,7,8,9,10])

b = np.roll(a,1)[0:4]

results in 结果是

>>> b
array([10  1  2  3])

As one of the answers mentioned, rolling the array makes a copy of the whole array which can be memory consuming for large arrays. 作为提到的答案之一,滚动数组会生成整个数组的副本,这可能是大型数组的内存消耗。 So just another way of doing this without converting to list is: 所以只需另一种方法,无需转换为列表即可:

np.concatenate([array[-1:],array[:3]])

Use np.r_ : 使用np.r_

import numpy as np
>>> 
>>> arr = np.arange(1, 11)
>>> arr[np.r_[-1:3]]
array([10,  1,  2,  3])

Simplest solution would be to convert first to list, and then join and return to array. 最简单的解决方案是首先转换为列表,然后加入并返回到数组。

As such: 因此:

>>> numpy.array(list(array[-1:]) + list(array[:3]))
array([10,  1,  2,  3])

This way you can choose which indices to start and end, without creating a duplicate of the entire array 这样,您可以选择要开始和结束的索引,而不会创建整个数组的副本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM