![]() |
卖萌的芹菜 · react-html2canvas-jspd ...· 7 月前 · |
![]() |
气宇轩昂的红薯 · 我的sql优化第一篇(当group_conc ...· 9 月前 · |
![]() |
心软的铁板烧 · 拼多多:新晋PUA之王?_创事记_新浪科技_新浪网· 9 月前 · |
![]() |
不羁的小刀 · 张昭军|“打孔家店”:从伦理觉悟到德性启蒙- ...· 11 月前 · |
![]() |
乐观的冲锋衣 · 超过Numpy的速度有多难?试试Numba的 ...· 1 年前 · |
如何从numpy数组中删除一些特定的元素?假设我有
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9])
然后我想从
a
中删除
3,4,7
。我只知道值的索引(
index=[2,3,6]
)。
发布于 2016-04-07 03:33:33
有一个numpy内置函数可以帮助你做到这一点。
import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.array([3,4,7])
>>> c = np.setdiff1d(a,b)
array([1, 2, 5, 6, 8, 9])
发布于 2019-04-26 17:43:13
要按值删除:
modified_array = np.delete(original_array, np.where(original_array == value_to_delete))
发布于 2012-06-12 20:06:15
不是一个麻木的人,我尝试了一下:
>>> import numpy as np
>>> import itertools
>>> a = np.array([1,2,3,4,5,6,7,8,9])
>>> index=[2,3,6]
>>> a = np.array(list(itertools.compress(a, [i not in index for i in range(len(a))])))
array([1, 2, 5, 6, 8, 9])
根据我的测试,它的性能优于
numpy.delete()
。我不知道为什么会出现这种情况,可能是因为初始数组太小了?
python -m timeit -s "import numpy as np" -s "import itertools" -s "a = np.array([1,2,3,4,5,6,7,8,9])" -s "index=[2,3,6]" "a = np.array(list(itertools.compress(a, [i not in index for i in range(len(a))])))"
100000 loops, best of 3: 12.9 usec per loop
python -m timeit -s "import numpy as np" -s "a = np.array([1,2,3,4,5,6,7,8,9])" -s "index=[2,3,6]" "np.delete(a, index)"