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

huangapple go评论60阅读模式
英文:

Shorthand index to get a cycle of a numpy array

问题

要在NumPy数组中索引所有元素并在最后包括第一个索引,可以使用以下代码:

import numpy as np
a = np.asarray([2, 4, 6])

# 一种解决方案是
cycle = np.append(a, a[0])

# 另一种解决方案是
cycle = a[[0, 1, 2, 0]]

# 另一种方法是使用切片操作
cycle = a[:]

请注意,第三种方法使用了切片操作,但没有包括索引0,如果要包括第一个索引,可以使用第一种或第二种方法。

英文:

I want to index all elements in a numpy array and also include the first index at the end. So if I have the array [2, 4, 6] , I want to index the array such that the result is [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]

答案1

得分: 2

另一个可能的解决方案:

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

输出:

[2 4 6 2]
英文:

Another possible solution:

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

Output:

[2 4 6 2]

huangapple
  • 本文由 发表于 2023年5月8日 01:56:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76195463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定