简体   繁体   English

从2D数组中删除单元格列表的最快方法

[英]Fastest numpy way to remove a list of cells from a 2d array

I have a very large 2D numpy array of mxn elements. 我有一个非常大的mxn元素2D numpy数组。 For each row, I need to remove exactly one element . 对于每一行,我需要删除一个元素 So for example from a 4x6 matrix I might need to delete [0, 1], [1, 4], [2, 3], and [3, 3] - I have this set of coordinates stored in a list. 因此,例如从4x6矩阵中,我可能需要删除[0,1],[1,4],[2,3]和[3,3]-我将这组坐标存储在列表中。 In the end, the matrix will ultimately shrink in width by 1. 最后,矩阵最终将在宽度上缩小1。

Is there a standard way to do this using a mask? 有使用口罩做到这一点的标准方法吗? Ideally, I need this to be as performant as possible. 理想情况下,我需要使它尽可能地表现出色。

Here is a method that use ravel_multi_index() to calculate one-dim index, and then delete() the elements, and reshape back to two-dim array: 这是一种使用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)

the index: 索引:

array([4, 6, 9, 0, 3, 5, 3, 8, 9, 8, 4, 4])

the result: 结果:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM