1

I have a numpy array A as follows:

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

and another numpy array column_indices_to_be_deleted as follows:

array([1, 0, 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]])

What would be the simplest way of doing that?

1 Answer 1

2

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

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

Another with 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]])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.