在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 个回答
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.