从2d数组中删除单元格列表的最快捷方式

时间:2018-02-20 03:18:46

标签: python numpy

我有一个非常大的2D numpy数组m x n个元素。对于每一行,我需要删除正好一个元素。因此,例如从4x6矩阵我可能需要删除[0,1],[1,4],[2,3]和[3,3] - 我将这组坐标存储在列表中。最后,矩阵的宽度最终会缩小1.

使用面具是否有标准方法可以做到这一点?理想情况下,我需要尽可能提高性能。

1 个答案:

答案 0 :(得分:0)

这是一种方法,使用ravel_multi_index()计算一个暗淡的索引,然后delete()个元素,reshape返回两个暗淡的数组:

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