假设我有两个数组:
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)
但我发现这有点棘手,因为我无法弄清楚如何跨 2 个数组逐元素映射 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])
