Home > Enterprise >  How to delete multiple value from matrix numpy low computational cost
How to delete multiple value from matrix numpy low computational cost

Time:07-13

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?

CodePudding user response:

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.]])
  • Related