首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将numpy布尔选择器限制为前几个真值的有效方法

将numpy布尔选择器限制为前几个真值的有效方法
EN

Stack Overflow用户
提问于 2019-07-12 01:33:27
回答 1查看 130关注 0票数 2

我有一个可以应用于数组a的numpy布尔selector数组。(在问题域中实际上不是随机的,这只是为了方便示例)。但我实际上希望仅使用selector的前n个True条目(在本例中为n=3 )进行选择。那么,给定selector加上一个参数n,如何使用select_first_few操作生成numpy,从而避免迭代循环?

代码语言:javascript
复制
>>> 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])
EN

回答 1

Stack Overflow用户

发布于 2019-07-12 01:46:40

获取列表中所有选定的索引,并对该列表进行切片。然后使用列表理解来检索这些选定索引处的数据。

代码语言:javascript
复制
import numpy as np
selector = np.random.random(10) > 0.5
data = np.arange(10)

choosen_indices = np.where(selector)

#select first 3 choosen
choosen_few_indices = choosen_indices[:3]
choosen_few = [data[i] for i in choosen_few_indices]

# if you are also interested in the not choosen data
not_choosen_indices = list(set(range(len(data))) - set(choosen_indices))
# proceed ...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56994591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档