Home > Net >  Delete the different rows in array with a loop
Delete the different rows in array with a loop

Time:04-14

I have a numpy array with multiple rows, I want to delete the rows with index 0, 1, 2 and 6 0, 6 1, 6 2, and 2 * 6 0, 2 * 6 1, and 2 * 6 2, and ... c * 6 0, c * 6 1, c * 6 2. I know that is possible to use the np.delete, however I don't know how to loop over the different indices. Here is an example:

a = np.array([[4, 5],
   [4, 2],
   [1, 2],
   [2, 3],
   [3, 1],
   [0, 1],
   [1, 1],
   [1, 0],
   [1, 5],
   [5, 4],
   [2, 3],
   [5, 5]])

The output which I want is :

out = np.array([
   [2, 3],
   [3, 1],
   [0, 1],
   [5, 4],
   [2, 3],
   [5, 5]])

CodePudding user response:

Instead of deleting, you could filter them out:

out = a[~np.isin(np.arange(len(a))%6, [0,1,2])]

Output:

array([[2, 3],
       [3, 1],
       [0, 1],
       [5, 4],
       [2, 3],
       [5, 5]])

CodePudding user response:

Here's a cheap way to do it. I combine sets of 6 rows, remove the left half, then restore the shape:

>>> a = np.array([[4, 5],    [4, 2],    [1, 2],    [2, 3],    [3, 1],    [0, 1],    [1, 1],    [1, 0],    [1, 5],    [5, 4],    [2, 3],    [5, 5]])
>>> a.shape
(12, 2)
>>> a.reshape((-1,12))
array([[4, 5, 4, 2, 1, 2, 2, 3, 3, 1, 0, 1],
       [1, 1, 1, 0, 1, 5, 5, 4, 2, 3, 5, 5]])
>>> a.reshape((-1,12))[:,6:]
array([[2, 3, 3, 1, 0, 1],
       [5, 4, 2, 3, 5, 5]])
>>> a.reshape((-1,12))[:,6:].reshape(-1,2)
array([[2, 3],
       [3, 1],
       [0, 1],
       [5, 4],
       [2, 3],
       [5, 5]])
>>>

reshape calls are cheap, so the only cost is in selecting the column subset.

  • Related