python - 在每个元素上使用条件的 Numpy 过滤器

标签 python numpy

我有一个过滤器表达式如下:
feasible_agents = filter(lambda agent: agent >= cost[task, agent], agents)
其中 agents 是一个 python 列表。

现在,为了加快速度,我正在尝试使用 numpy 来实现这一点。

使用 numpy 的等价物是什么?

我知道这有效:

threshold = 5.0
feasible_agents = np_agents[np_agents > threshold]

其中 np_agentsagents 的numpy等价物。

但是,我希望阈值是 numpy 数组中每个元素的函数。

最佳答案

由于您没有提供示例数据,请使用玩具数据:

# Cost of agents represented by indices of cost, we have agents 0, 1, 2, 3
cost = np.array([4,5,6,2])
# Agents to consider 
np_agents = np.array([0,1,3])
# threshold for each agent. Calculate different thresholds for different agents. Use array of indexes np_agents into cost array.
thresholds = cost[np_agents] # np.array([4,5,2])
feasible_agents = np_agents[np_agents > thresholds] # np.array([3])

关于python - 在每个元素上使用条件的 Numpy 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52380972/

相关文章:

python - 为什么 blas 比 numpy 慢

python-2.7 - DNNCLassifier Tensorflow 上的 label_keys 类型错误

python - 导入错误 : Missing required dependencies ['numpy' ]

datetime - 以下哪一个是 pythonic 的? Pythonic 与速度

python - “assert False”和 “self.assertFalse”有什么优势或区别

python - 使用python抓取html元素的内部标签时出错

python - numpy.tolist() 和 list() 之间精度/显示的差异

python - 如何在列表中查找重复项及其索引?

python xlsxwriter 更改工作表中所有行的行高

python - 为什么在 MNIST 教程中使用负 reshape (-1)?