【发布时间】:2019-11-21 11:47:02
【问题描述】:
我有一个 numpy boolean selector 数组,我可以将其应用于数组 a。 (实际上在问题域中不是随机的,这只是为了方便示例)。但我实际上只想使用 selector 的前 n 个 True 条目进行选择(示例中最多为 n=3)。那么给定selector加上参数n,如何使用numpy操作生成select_first_few,从而避免迭代循环?
>>> import numpy as np
>>> selector = np.random.random(10) > 0.5
>>> a = np.arange(10)
>>> selector
array([ True, False, True, True, True, False, True, False, True,
False])
>>> chosen, others = a[selector], a[~selector]
>>> chosen
array([0, 2, 3, 4, 6, 8])
>>> others
array([1, 5, 7, 9])
>>> select_first_few = np.array([ True, False, True, True, False, False, False, False, False,
... False])
>>> chosen_few, tough_luck = a[select_first_few], a[~select_first_few]
>>> chosen_few
array([0, 2, 3])
>>> tough_luck
array([1, 4, 5, 6, 7, 8, 9])
【问题讨论】:
-
切片结果?
-
我可以看到它如何生成
chosen_few但不能生成tough_luck