假设我有两个数组:
import numpy as np
a = np.random.randint(0,10,10)
b = np.random.randint(0,10,10)
我想生成另一个长度为 10 的数组,其第 i 个条目是从集合中抽取的随机整数({0...9}
减去 元素a[i]
和 b[i]
)。
作为 NumPy 的新手,我认为最简单的方法可能是:
- 获取每个
i
的集合差值x = {0...9} - (a[i] union b[i])
- 对每个
i
执行np.random.choice(x[i], 1)
但我发现这有点棘手,因为我无法弄清楚如何在两个数组之间按元素映射 setdiff1d
。在 NumPy 中是否有一种明显的方法可以做到这一点(即理想情况下不必求助于 Python 集等)?
最佳答案
这是一种方法:
In [87]: col = np.array((a, b)).T # Or as a better way np.column_stack((a,b)); suggested by @Divakar
In [88]: r = np.arange(10)
In [89]: np.ravel([np.random.choice(np.setdiff1d(r, i), 1) for i in col])
Out[89]: array([7, 8, 8, 6, 6, 8, 6, 5, 5, 6])
或者作为 numpytonic 方法:
In [101]: def func(x):
return np.random.choice(np.setdiff1d(r, x), 1)
.....:
In [102]: np.apply_along_axis(func, 1, col).ravel()
Out[102]: array([6, 7, 9, 6, 4, 6, 7, 4, 0, 7])
关于python - 从一组数字中抽取一个随机数,排除某些组中给出的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39438582/