Skip to main content
 首页 » 编程设计

python之Numpy 从 2 个数组中选择元素

2025年05月04日15unruledboy

我需要从 2 个数组中选择 n 个项目,以使索引相同。因此,例如,我需要从 x 中随机选择两个项目,并从 y 中选择元素,使得 y 的选择索引与 x 的相同:

x = np.asarray([0.1123,0.223,0.8873]) 
y = np.asarray([1,1,2]) 
 
x_chosen = np.random.choice(x,(2,)) 

假设 x_chosen 结果是:x_chosen = [0.1123,0.223]... 那么我需要:

y_chosen = [1,1] 

我目前有一个解决方法……但我想要一个基本的 numpy 或 scipy 函数,而不是我自己的基本上只有 3 行的函数,以使我在这个项目中的函数保持在范围内……我宁愿我的主要代码中没有这种一次性变量创建:

x_index = np.asarray([i for i in range(len(x))]) 
x_chosen_indices = np.random.choice(x_index,(2,)) 
x_chosen = x[x_chosen_indices] 
y_chosen = y[x_chosen_indices] 

或者,我可以堆叠、选择和拆分...但我想这仍然给我留下了一个一次性函数,我必须坚持在某个地方...或 4-5 行没有意义的代码...

请您参考如下方法:

使用 np.random.randint() 找到您的索引:

x = np.asarray([0.1123,0.223,0.8873]) 
y = np.asarray([1,1,2]) 
 
indices = np.random.randint(0, x.size, 2) 
>>> x[indices] 
array([ 0.1123,  0.223 ]) 
>>> y[indices] 
array([1, 1]) 

编辑

正如 B.M 在评论中提到的,使用 np.random.choice(.., replace=False) 来 避免多次使用相同的索引:

indices = np.random.choice(x.size, 2, replace=False)