获取numpy数组的循环的速记索引

3
我想索引numpy数组中的所有元素,并在末尾包括第一个索引。因此,如果我有数组[2, 4, 6],我希望索引数组,使结果为[2, 4, 6, 2]
import numpy as np
a = np.asarray([2,4,6])

# One solution is 
cycle = np.append(a, a[0])

# Another solution is 
cycle = a[[0, 1, 2, 0]]

# Instead of creating a list, can indexing type be combined?
cycle = a[:+0]

你需要对切片结果进行某种连接,或者使用包含所有部分的数组进行高级索引。单个基本索引无法引用数组的不连续部分。 - hpaulj
1个回答

2

另一个可能的解决方案:

a = np.asarray([2,4,6])
cycle = np.take(a, np.arange(len(a)+1), mode='wrap')

输出:

[2 4 6 2]

1
谢谢,mode='wrap'正是我寻找的。 - nikost

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接