Python / Numpy - 在数组末尾包裹切片

时间:2011-04-16 01:32:43

标签: python indexing numpy slice

我有两个1D数组,一个有一些感兴趣的值(a),另一个为该数组提供索引(b)。我知道b中的值总是增加,除了在数字减少的一个点(可能是任何地方),因为它从数组a的末尾滚动到数组的开头。下面的方法似乎有效,但我认为必须采用更清洁的方式。谁能提出更好的建议?感谢。

代码:

import numpy as np
a = np.arange(12)
b = np.array([5, 9, 2, 4])
#I want to generate these:
#[5,6,7,8,9]
#[9,10,11,0,1,2]
#[2,3,4]
#[4,5]

a = np.roll(a, -b[0], axis=0)
# Subtract off b[0] but ensure that all values are positive
b = (b-b[0]+len(a))%len(a)
for i, ind in enumerate(b):
   if i < len(b)-1:
      print a[b[i]:b[i+1]+1]
   else:
      print np.hstack((a[b[i]:len(a)], a[0]))

2 个答案:

答案 0 :(得分:3)

有点短,但也许我还能做得更好......

import numpy as np

a = np.arange(12)
b = np.array([5, 9, 2, 4])
b = np.append(b, b[0])

for i in range(0, len(b)-1):
    print np.roll(a, len(a)-b[i])[:b[i+1]-b[i]+1]

答案 1 :(得分:0)

不确定这是否有帮助,但是如果没有弄乱a的记忆就会快速解决这个问题:

import numpy as np

a = np.arange(12)
b = np.array([5, 9, 2, 4])
b = np.append(b, b[0])

b2 = b.copy()

b2[(np.diff(b)<0).nonzero()[0]+1:] += a.size

print [np.take(a, np.r_[b2[i]:b2[i+1]+1], mode='wrap') for i in range(b.size-1)]

print [np.roll(a, len(a)-b[i])[:b[i+1]-b[i]+1] for i in range(b.size-1)]

%timeit [np.take(a, np.r_[b2[i]:b2[i+1]+1], mode='wrap') for i in range(b.size-1)]
# 10000 loops, best of 3: 28.6 µs per loop

%timeit [np.roll(a, len(a)-b[i])[:b[i+1]-b[i]+1] for i in range(b.size-1)]
# 10000 loops, best of 3: 77.7 µs per loop