Wol*_*lph 20
如何使用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]]
Run Code Online (Sandbox Code Playgroud)
所有这些答案对我来说似乎有点令人费解。
我假设您有一个多维数组,您想从中生成详尽的索引列表。您希望对这些索引进行打乱,以便您可以按随机顺序访问每个数组元素。
以下代码将以简单直接的方式执行此操作:
#!/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
Run Code Online (Sandbox Code Playgroud)
打印d验证所有元素均已被访问。
请注意,数组可以具有任意数量的维度,并且维度可以是任意大小。
这种方法的唯一缺点是,如果d很大,那么indices可能会变得相当大。因此,如果有一台发电机就好了。可悲的是,我无法立即想到如何构建一个打乱的迭代器。
| 归档时间: |
|
| 查看次数: |
13426 次 |
| 最近记录: |