数组的每一行中删除指定的列索引

数组的每一行中删除指定的列索引

本文介绍了从二维 numpy 数组的每一行中删除指定的列索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 numpy 数组 A,如下所示:

I have a numpy array A as follows:

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

和另一个 numpy 数组 column_indices_to_be_deleted 如下:

and another numpy array column_indices_to_be_deleted as follows:

array([1, 0, 2])

我想从 column_indices_to_be_deleted 中的列索引指定的 A 的每一行中删除元素.因此,在这种情况下,第 0 行的列索引 1、第 1 行的列索引 0 和第 2 行的列索引 2,以获得如下所示的新数组:

I want to delete the element from every row of A specified by the column indices in column_indices_to_be_deleted. So, column index 1 from row 0, column index 0 from row 1 and column index 2 from row 2 in this case, to get a new array that looks like this:

array([[1, 3],
       [5, 6],
       [7, 8]])

最简单的方法是什么?

推荐答案

One way with masking created with broadcatsed-comparison -

One way with masking created with broadcatsed-comparison -

In [43]: a # input array
Out[43]:
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In [44]: remove_idx # indices to be removed from each row
Out[44]: array([1, 0, 2])

In [45]: n = a.shape[1]

In [46]: a[remove_idx[:,None]!=np.arange(n)].reshape(-1,n-1)
Out[46]:
array([[1, 3],
       [5, 6],
       [7, 8]])

另一种基于 mask 的方法,使用 array-assignment -

Another mask based approach with the mask created with array-assignment -

In [47]: mask = np.ones(a.shape,dtype=bool)

In [48]: mask[np.arange(len(remove_idx)), remove_idx] = 0

In [49]: a[mask].reshape(-1,a.shape[1]-1)
Out[49]:
array([[1, 3],
       [5, 6],
       [7, 8]])

另一个带有 np.delete -

In [64]: m,n = a.shape

In [66]: np.delete(a.flat,remove_idx+n*np.arange(m)).reshape(m,-1)
Out[66]:
array([[1, 3],
       [5, 6],
       [7, 8]])

这篇关于从二维 numpy 数组的每一行中删除指定的列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:00