Home > Back-end >  numpy delete rows not in list
numpy delete rows not in list

Time:02-24

Here is my code to delete given row numbers

a = np.arange(12).reshape(6, 2)
b = [1, 4]
a: [[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]]

then i delete the lines in b :

np.delete(a, b, 0)

output : 
array([[ 0,  1],
       [ 4,  5],
       [ 6,  7],
       [10, 11]])

I want to use this logic to only keep the rows in b, and do the reverse operation without any loop.
so expected output will be :

output: [
 [ 2,  3]
 [ 8,  9]
 ]

CodePudding user response:

IIUC, splitting the array a using the indices in b:

a2 = a[b]
a1 = np.delete(a,b,0)

output:

# a1
array([[ 0,  1],
       [ 4,  5],
       [ 6,  7],
       [10, 11]])

# a2
array([[2, 3],
       [8, 9]])

restoring the original array from a1, a2, and b:

idx = np.arange(a1.shape[0] a2.shape[0])
idx = np.r_[np.delete(idx,b,0),idx[b]]

new_a = np.r_[a1,a2][np.argsort(idx)]

output:

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

CodePudding user response:

The answer is just to keep the wanted rows in b by doing:

x = a[b,:]

Don't delete unwanted rows but just select the needed one

  • Related