在numpy中随机选择索引位置

时间:2014-04-12 03:55:00

标签: python numpy

import numpy as np
data  = np.array([[0,1,2,3,4,7,6,7,8,9,10], 
    [3,3,3,4,7,7,7,8,11,12,11],  
    [3,3,3,5,7,7,7,9,11,11,11],
    [3,4,3,6,7,7,7,10,11,17,11],
    [4,5,6,7,7,9,10,11,11,11,11]])
required = np.where(data==11)
print required

(array([1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4], dtype=int64), array([ 8, 10,  8,  9, 10,  8, 10,  7,  8,  9, 10], dtype=int64))

必需如何随机选择(不再发生)只有3个索引位置?

答案应该是索引位置作为必需的子集。

我的审判:

result = np.random.choice(required, 3, replace=False)
print result

ValueError: a must be 1-dimensional

解决这个问题的任何想法???

1 个答案:

答案 0 :(得分:1)

这可以完成这项工作:

import numpy as np
data  = np.array([[0,1,2,3,4,7,6,7,8,9,10], 
     [3,3,3,4,7,7,7,8,11,12,11],  
     [3,3,3,5,7,7,7,9,11,11,11],
     [3,4,3,6,7,7,7,10,11,17,11],
     [4,5,6,7,7,9,10,11,11,11,11]])
required = np.where(data==11)

coords = zip(required[0], required[1]) #Create pairs of indices as tuples
for i in np.random.choice(len(coords), 3, replace=False): #Pick random index values for coords
    print coords[i] #May want to do something other than printing here.