Fast and efficient slice of the array, eliminating the delete operation

I am trying to get a slice (e.g. elements 1-3 and 5-N) of array A (N, 3), avoiding using numpy.delete. And an example process would be:

 [[1,2,3],[4,5,6],[7,8,9],[3,2,1]] ==>  [[1,2,3],[3,2,1]]

I was hoping to use something like

A[A != [1,2,3] ].reshape()

But this does an elemental comparison and thus removes more elements than I wanted. How to do it? I came up with this idea, but it seems too complicated and slow:

A_removed = A[first_removed:last:removed,:] 
mask      = np.not_equal(A[:,None],A_removed)
mask      = np.logical_and.reduce(mask,1)
A         = A[mask].reshape()

Is there any way to make this faster / cleaner?

PD statement that any two elements of A cannot be equal always holds

+3
source share
1 answer

Edit

While re-reading the question, I am now almost sure that the OP wants to get a backlink to what I originally posted. Here is how you understand it:

import numpy as np

def selectRow(arr, selrow):
    selset = set(selrow)
    return np.array([row for row in arr if selset == set(row)])

arr = np.array([
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [3,2,1]
])

selectRow(arr, [1,2,3])

:

array([[1, 2, 3],
       [3, 2, 1]])

, , .

:

import numpy as np

def withoutRow(arr, badrow):
    return np.array([row for row in arr if not np.array_equal(row, badrow)])

:

arr = np.array([
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [3,2,1]
])

withoutRow(arr, [1,2,3])

:

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

withoutRow ( ), ( ), ( ).

, :

def withoutRowUnordered(arr, badrow):
    badset = set(badrow)
    return np.array([row for row in arr if badset != set(row)])

withoutRowUnordered(arr, [1,2,3])

:

array([[4, 5, 6],
       [7, 8, 9]])
+1

Source: https://habr.com/ru/post/1696337/


All Articles