[英]How to get all possible shuffle combinations using numpy
我有一个长度为N
的 NumPy 数组,其中包含X
个 1 和NX
个零。 我想生成我的数组的所有可能的随机播放组合。
例如,当N
为 5 且X
为 2 时,我需要以下组合,
[0, 0, 1, 1, 0]
[1, 1, 0, 0, 0]
[0, 0, 0, 1, 1]
[0, 0, 1, 0, 1]
[1, 0, 0, 1, 0]
[0, 1, 1, 0, 0]
[0, 1, 0, 1, 0]
[1, 0, 1, 0, 0]
[0, 1, 0, 0, 1]
[1, 0, 0, 0, 1]
在 numpy 中是否有任何直接的方法可以做到这一点?
组合在itertools
的 Python 标准库中实现。 它从N
列表中选择X
元素,因此您可以让它选择索引并将其设置为1
:
import numpy as np
from itertools import combinations
N = 5
X = 2
for combination in combinations(range(N), X):
arr = np.zeros(N)
arr[list(combination)] = 1
print(arr)
Output:
[1. 1. 0. 0. 0.]
[1. 0. 1. 0. 0.]
[1. 0. 0. 1. 0.]
[1. 0. 0. 0. 1.]
[0. 1. 1. 0. 0.]
[0. 1. 0. 1. 0.]
[0. 1. 0. 0. 1.]
[0. 0. 1. 1. 0.]
[0. 0. 1. 0. 1.]
[0. 0. 0. 1. 1.]
这是一个带有itertools.combinations
的矢量化 -
from itertools import combinations
def combs(N, X):
idx = np.array(list(combinations(range(N), X)))
n = len(idx)
out = np.zeros((n,N), dtype=int)
out[np.arange(n)[:,None],idx] = 1
return out
样品运行 -
In [57]: combs(N=5, X=2)
Out[57]:
array([[1, 1, 0, 0, 0],
[1, 0, 1, 0, 0],
[1, 0, 0, 1, 0],
[1, 0, 0, 0, 1],
[0, 1, 1, 0, 0],
[0, 1, 0, 1, 0],
[0, 1, 0, 0, 1],
[0, 0, 1, 1, 0],
[0, 0, 1, 0, 1],
[0, 0, 0, 1, 1]])
In [58]: combs(N=5, X=3)
Out[58]:
array([[1, 1, 1, 0, 0],
[1, 1, 0, 1, 0],
[1, 1, 0, 0, 1],
[1, 0, 1, 1, 0],
[1, 0, 1, 0, 1],
[1, 0, 0, 1, 1],
[0, 1, 1, 1, 0],
[0, 1, 1, 0, 1],
[0, 1, 0, 1, 1],
[0, 0, 1, 1, 1]])
In [59]: combs(N=5, X=4)
Out[59]:
array([[1, 1, 1, 1, 0],
[1, 1, 1, 0, 1],
[1, 1, 0, 1, 1],
[1, 0, 1, 1, 1],
[0, 1, 1, 1, 1]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.