python - 替换numpy数组中多个元素的最快方法
问题描述
根据列表替换数组中的值的简单示例:
import numpy as np
l = [1,3,4,15]
a = np.array([1,1,2,4,6,7,8,9,1,2,3,4,89,12,23,3,4,10,15])
for element in l:
a = np.where(a == element, 0, a)
由于这相当慢,我正在寻找一种更快的替代方案,它可以很好地扩展。
解决方案
numpy.where
与 一起使用numpy.isin
:
np.where(np.isin(a, l), 0, a)
输出:
array([ 0, 0, 2, 0, 6, 7, 8, 9, 0, 2, 0, 0, 89, 12, 23, 0, 0,
10, 0])
推荐阅读
- assembly - 访问 MASM 中的位
- python - 尝试按月对数据框进行排序时重新索引导致 NaN 值
- typescript - 我使用的是哪个版本的打字稿,全局的还是本地的?
- css - css div到完整的视口高度并且没有滚动条
- javascript - 自定义 v-data-table 标题并保留默认功能(排序)
- reactjs - 我如何测试使用效果周期?看看和一张桌子
- c# - 通过 SignalR HubContext 从集线器所在的项目中的方法发送消息
- java - 读入用户输入的值时,什么是 IOException?
- html - Gmail 中的 HTML 模板呈现不正确
- python - 在 Python 中寻找模式