1

I have a N*K dimensional numpy array X and want to construct N*(K-1) dimensional numpy array Y by removing the element 1 of the first row, element 3 of the second row, element 1 of the forth row .... element j on the Nth row. The indices of th elements should be removed are stored in a N*1 dimensional vector t. Is there an easy way to do this?

1 Answer 1

1

You could build a boolean selection mask:

mask = np.ones_like(X, dtype='bool')
mask[np.arange(X.shape[0]), idx] = 0

which would make defining Y and t easy:

import numpy as np
N, K = 3, 4
X = np.arange(N*K).reshape(N,K)
# idx indicates which element you wish to remove from each row
idx = np.arange(N)

mask = np.ones_like(X, dtype='bool')
mask[np.arange(X.shape[0]), idx] = 0

Y = X[mask].reshape(N, K-1)
t = X[~mask]

yields

In [17]: X
Out[17]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [15]: Y
Out[15]: 
array([[ 1,  2,  3],
       [ 4,  6,  7],
       [ 8,  9, 11]])

In [16]: t
Out[16]: array([ 0,  5, 10])
Sign up to request clarification or add additional context in comments.

1 Comment

an elegant answer. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.