0

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]
 ]
2
  • 2
    Why do you want to delete the rows? why not use a[b] to accses the part you need? You can get the desired result by a=a[b] Commented Feb 22, 2022 at 13:55
  • 1
    np.delete internally figures out which rows you want to keep, and returns those. So keeping the the b rows is actually simpler - conceptually and computationally. Commented Feb 22, 2022 at 16:55

2 Answers 2

0

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

Comments

0

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

Comments

Your Answer

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