首页 > 解决方案 > 替换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)

由于这相当慢,我正在寻找一种更快的替代方案,它可以很好地扩展。

标签: pythonnumpy

解决方案


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])

推荐阅读