np.choose(a, choices, out=None, mode='raise'):按照序号a对choices中的数进行选择。
a: index array,其中的数必须是整数
mode=‘raise’,表示a中数必须在[0,n-1]范围内
mode=‘wrap’,a中数可以是任意的整数(signed),对n取余映射到[0,n-1]范围内
mode='clip',a中数可以是任意的整数(signed),负数映射为0,大于n-1的数映射为n-1
Example 1:
来自np.choose官方文档的例子,对list进行choose:
a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
choices = [-10, 10]
np.choose(a, choices)
array([[ 10, -10, 10],
[-10, 10, -10],
[ 10, -10, 10]])
Example 2:
除了可以用于list,choose还可以用于np.array类型。
在机器学习中,通常a每行为一个sample,列数代表不同的feature。index中保存每个sample需要选出feature的序号。
那么可以通过以下操作在a中选出所有sample的目标feature:
a = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
index = np.array([0,2,1,0])
np.choose(index,a.T)
array([ 1, 6, 8, 10])