1

I've recently been trying my hand at numpy, and I'm trying to find a solution to delete the elements inside the matrix at column 2 equal to the value stored in the variable element. Since I am a large amount of data I would need to know if there was a more efficient method which takes less time to execute than the classic for. I enclose an example:

element = [ 85.,  222., 166., 238.]

matrix = [[228.,   1., 222.],
          [140.,   0.,  85.],
          [140.,   0., 104.],
          [230.,   0., 217.],
          [115.,   1., 250.],
          [12.,    1., 166.],
          [181.,   1., 238.]]

the output:

matrix = [[140.,   0., 104.],
          [230.,   0., 217.],
          [115.,   1., 250.]]

The method I used is the following:

for y in element:
    matrix = matrix[(matrix[:,2]!= y)]

When running it for a large amount of data it takes a long time. Is there anything more efficient, so that you can save on execution?

1 Answer 1

1

Since you tagged numpy, I'd assume matrix is a numpy array. With that, you can use np.isin for your purpose:

matrix = np.array(matrix)

matrix[~np.isin(np.array(matrix)[:,2], element)]

Output:

array([[140.,   0., 104.],
       [230.,   0., 217.],
       [115.,   1., 250.]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it's much better now, you have been so helpful to me. But could I add descending sorting to this function?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.