python - 替换 numpy 数组中多个元素的最快方法

标签 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)

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

最佳答案

您可以使用np.wherenp.in1d :

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

关于python - 替换 numpy 数组中多个元素的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60110135/

相关文章:

python - 是否可以在 Django 中制作移动应用程序?

python - 在Python中,如何分割字符串并保留分隔符?

python - 将层次结构添加到 numpy 结构化数组

python - 3D 数据的最佳数据结构?

python - 使用对象数组进行条件索引

python - 分隔 numpy 数组中的数字,这些数字用单引号括起来,并用空格分隔

python - 使用 Python 3 ElementTree 的 XML 文档中的多个命名空间

python - 在另一个线程中在 python3 中运行的非阻塞套接字服务器

python - 是否可以在 pandas 数据框中格式化字符串?

python - 在 numba 函数中使用 np.min 和列表输入