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?
Add a comment
|
1 Answer
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])
1 Comment
TNM
an elegant answer. Thanks.