替换numpy阵列中多个元素的最快方法

2024-06-09 03:30:05 发布

您现在位置:Python中文网/ 问答频道 /正文

根据列表替换数组中的值的简单示例:

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)

由于这是相当缓慢,我正在寻找一个更快的替代方案,规模很好


Tags: inimportnumpy示例列表forasnp
3条回答

^{}^{}一起使用:

a = np.where(np.isin(a, l), 0, a)
print(a)

输出:

[ 0  0  2  0  6  7  8  9  0  2  0  0 89 12 23  0  0 10  0]

如果您的numpy版本小于1.13.0,请使用@yatu的答案

documentation's注释中所述:

New in version 1.13.0.

numpy.wherenumpy.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])

可以将^{}^{}一起使用:

np.where(np.in1d(a, l), 0, a)

array([ 0,  0,  2,  0,  6,  7,  8,  9,  0,  2,  0,  0, 89, 12, 23,  0,  0,
       10,  0])

相关问题 更多 >