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

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

Shorthand index to get a cycle of a numpy array

问题

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

  1. import numpy as np
  2. a = np.asarray([2, 4, 6])
  3. # 一种解决方案是
  4. cycle = np.append(a, a[0])
  5. # 另一种解决方案是
  6. cycle = a[[0, 1, 2, 0]]
  7. # 另一种方法是使用切片操作
  8. 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].

  1. import numpy as np
  2. a = np.asarray([2,4,6])
  3. # One solution is
  4. cycle = np.append(a, a[0])
  5. # Another solution is
  6. cycle = a[[0, 1, 2, 0]]
  7. # Instead of creating a list, can indexing type be combined?
  8. cycle = a[:+0]

答案1

得分: 2

另一个可能的解决方案:

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

输出:

  1. [2 4 6 2]
英文:

Another possible solution:

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

Output:

  1. [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:

确定