[英]Fastest numpy way to remove a list of cells from a 2d array
我有一個非常大的mxn元素2D numpy數組。 對於每一行,我需要刪除一個元素 。 因此,例如從4x6矩陣中,我可能需要刪除[0,1],[1,4],[2,3]和[3,3]-我將這組坐標存儲在列表中。 最后,矩陣最終將在寬度上縮小1。
有使用口罩做到這一點的標准方法嗎? 理想情況下,我需要使它盡可能地表現出色。
這是一種使用ravel_multi_index()
計算一ravel_multi_index()
引,然后delete()
元素,並reshape
ravel_multi_index()
為二維數組的方法:
import numpy as np
n = 12
a = np.repeat(np.arange(10)[None, :], n, axis=0)
index = np.random.randint(0, 10, n)
ravel_index = np.ravel_multi_index((np.arange(n), index), a.shape)
np.delete(a, ravel_index).reshape(n, -1)
索引:
array([4, 6, 9, 0, 3, 5, 3, 8, 9, 8, 4, 4])
結果:
array([[0, 1, 2, 3, 4, 5, 6, 7, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 9],
[0, 1, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[0, 1, 2, 4, 5, 6, 7, 8, 9]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.