从NumPy数组中随机选择单元格 - 不重复
我正在用NumPy写一些建模程序,需要从一个NumPy数组中随机选择单元格,并对它们进行处理。所有单元格必须是无重复选择的,也就是说,一旦选择了一个单元格,就不能再选择它,但最终所有单元格都必须被选择。
我之前用IDL做这个,那里有很好的方法来实现,但我想NumPy也应该有类似的好方法。你有什么建议吗?
更新:我应该说明一下,我是在处理二维数组,因此我需要返回一组二维的索引。
6 个回答
2
这里是对@WoLpH的一个很好的回答的扩展。
对于一个二维数组,你想知道索引的信息会影响你的方法。
你可以这样做:
data = np.arange(25).reshape((5,5))
x, y = np.where( a = a)
idx = zip(x,y)
np.random.shuffle(idx)
或者
data = np.arange(25).reshape((5,5))
grid = np.indices(data.shape)
idx = zip( grid[0].ravel(), grid[1].ravel() )
np.random.shuffle(idx)
然后你可以使用列表 idx
来按你想要的顺序遍历二维数组的索引,并从不变的 data
中获取该索引的值。
注意: 如果你对 itertools.product
这个工具更熟悉,你也可以用它来生成随机顺序的索引。
6
这些回答对我来说有点复杂。
我假设你有一个多维数组,你想从中生成一个完整的索引列表。你希望这些索引是随机打乱的,这样你就可以以随机的顺序访问数组中的每个元素。
下面的代码可以简单明了地实现这个功能:
#!/usr/bin/python
import numpy as np
#Define a two-dimensional array
#Use any number of dimensions, and dimensions of any size
d=numpy.zeros(30).reshape((5,6))
#Get a list of indices for an array of this shape
indices=list(np.ndindex(d.shape))
#Shuffle the indices in-place
np.random.shuffle(indices)
#Access array elements using the indices to do cool stuff
for i in indices:
d[i]=5
print d
打印 d
可以确认所有元素都被访问过了。
请注意,这个数组可以有任意数量的维度,而且每个维度的大小也可以不同。
这种方法唯一的缺点是,如果 d
很大,那么 indices
可能会变得相当庞大。因此,如果能有一个生成器就好了。不过,我一时想不出怎么快速构建一个打乱的迭代器。
21
如果你还需要保留原来的数组,可以考虑使用 numpy.random.shuffle
或 numpy.random.permutation
。
如果你想直接在原数组上进行修改,可以像这样创建一个索引数组:
your_array = <some numpy array>
index_array = numpy.arange(your_array.size)
numpy.random.shuffle(index_array)
print your_array[index_array[:10]]