简体   繁体   English

通过循环迭代 numpy 数组的元素

[英]Iterating elements of a numpy array by cycling

I have a pretty straightforward question that I couldn't figure out quickly from the numpy reference documentation.我有一个非常简单的问题,我无法从 numpy 参考文档中快速弄清楚。

Say I have a numpy array labels = np.array([1, 2, 3]) .假设我有一个 numpy 数组labels = np.array([1, 2, 3])
I have another array arr = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3]) .我有另一个数组arr = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3])
I'd like to randomly sample indices of arr .我想随机抽样arr的索引。 Say our indices are [0, 3, 6] .假设我们的索引是[0, 3, 6]

Now, I'd like to make the elements corresponding to those indices cycle by one in labels .现在,我想让与这些索引相对应的元素在labels中循环一个。 So, since arr[0] == 1 , we would set arr[0] = 2 .因此,由于arr[0] == 1 ,我们将设置arr[0] = 2 Since arr[3] == 2 , we would set arr[3] = 3 .由于arr[3] == 2 ,我们将设置arr[3] = 3 Since arr[6] == 3 , we would set arr[6] = 1 .由于arr[6] == 3 ,我们将设置arr[6] = 1

so, to recap:所以,回顾一下:

arr = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3])
labels = np.unique(arr)
idx = np.array([0, 3, 6])  # randomly generate indices [0, 3, 6]
new_arr == np.array(2, 1, 1, 3, 2, 2, 1, 3, 3])  # this is the array I want

This seems like it'd be pretty straightforward, but I can't find an elegant way of doing this quickly!这似乎很简单,但我找不到快速做到这一点的优雅方式!

If I understood you right, you might combine np.roll with np.random.randint , ie:如果我理解正确,您可以将np.rollnp.random.randint结合使用,即:

sample_idx = np.roll(np.random.randint(len(arr), 3), shift=1)                                                                                                                                                                                            
sample = [labels[i] for i in sample_idx]

That is, randomly sample 3 indexes and roll them by one.也就是说,随机抽取 3 个索引并将它们滚动一个。 This should be the final indexes to be re-mapped to your labels.这应该是要重新映射到标签的最终索引。

EDIT编辑

Got it.知道了。 You might do it in two steps:您可以分两步完成:

new_arr = arr.copy()
new_arr[idx] = np.roll(labels, -1)  # fixed the shift to -1

Output: Output:

array([2, 1, 1, 3, 2, 2, 1, 3, 3])

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

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