Home > Back-end >  Numpy delete all rows that start with zero
Numpy delete all rows that start with zero

Time:04-07

I have 2D Numpy array, I would like to delete all rows that start with certain value let say (0), then keep all rows that start with other value let say (10) into new array

a1 = np.array([[ 0,  1,  2,  3,  4],
   [ 5,  6,  0,  8,  0],
   [10, 11, 12, 13, 14],
   [ 0, 16, 17, 18, 19],
   [20, 21, 22,  0, 24]])

after first step

a2 = ([[ 5,  6,  0,  8,  0],
      [10, 11, 12, 13, 14],
      [20, 21, 22,  0, 24]])

last step

a3 = ([[10, 11, 12, 13, 14]])

CodePudding user response:

You can achieve this with the following masks:

mask = (a1[:, 0] != 0)
a2 = a1[mask, :]

mask2 = (a2[:, 0] == 10)
a3 = a2[mask2, :]

CodePudding user response:

you can use the np.logical_not method to create the conditions for the rows you want to remove.

'''

a2 = a1[np.logical_not(a1[:, 0] == 0)]
a3 = a2[np.logical_not(a2[:, 0] != 10)]

'''

  • Related