![]() |
痴情的火龙果 · 臺灣外來種鳥類名錄 | 社團法人中華民國野鳥學會· 16 小时前 · |
![]() |
火星上的海豚 · 福建宁德蕉城区可能区划调整_闽东· 10 月前 · |
![]() |
含蓄的汽水 · 泄密案件查处办法-甘肃省地震局单位门户网站· 12 月前 · |
![]() |
英姿勃勃的冲锋衣 · “大肉”VS“猪肉”,大家到底在争什么? - 知乎· 1 年前 · |
![]() |
温柔的草稿纸 · Kong, 502 Bad Gateway ...· 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)"
![]() |
痴情的火龙果 · 臺灣外來種鳥類名錄 | 社團法人中華民國野鳥學會 16 小时前 |
![]() |
火星上的海豚 · 福建宁德蕉城区可能区划调整_闽东 10 月前 |
![]() |
含蓄的汽水 · 泄密案件查处办法-甘肃省地震局单位门户网站 12 月前 |