1

I have a list of integers which represent positions in a matrix (centre). For example,

centre = [2, 50, 100, 89]

I also have two numpy matrices, X and Y. I need to delete all of the rows from the matrix if the number is in the centre. I can do this:

for each in centre:
  x = numpy.delete(x, (each), axis=0)

However, the numbers will all be out as the index's will all be out. So, how can I do this?

1 Answer 1

3

Just do the delete in one call:

In [266]: B
Out[266]: 
array([[ 2,  4,  6],
       [ 8, 10, 12],
       [14, 16, 18],
       [20, 22, 24]])
In [267]: B1=np.delete(B,[1,3],axis=0)
In [268]: B1
Out[268]: 
array([[ 2,  4,  6],
       [14, 16, 18]])

You question is a little confusing. I'm assuming that you want to delete rows by index number, not by some sort of content (not like the list find).

However if you must iterate (as with a list) do it in reverse order - that way indexing doesn't get messed up. You may have to sort the indices first (np.delete doesn't require that).

In [269]: B1=B.copy()
In [270]: for i in [1,3][::-1]:
     ...:     B1=np.delete(B1,i,axis=0)

A list example that has to be iterative:

In [276]: B1=list(range(10))
In [277]: for i in [1,3,5,7][::-1]:
     ...:     del B1[i]
In [278]: B1
Out[278]: [0, 2, 4, 6, 8, 9]

=============

With a list input like this, np.delete does the equivalent of:

In [285]: mask=np.ones((4,),bool)
In [286]: mask[[1,3]]=False
In [287]: mask
Out[287]: array([ True, False,  True, False], dtype=bool)
In [288]: B[mask,:]
Out[288]: 
array([[ 2,  4,  6],
       [14, 16, 18]])
Sign up to request clarification or add additional context in comments.

Comments

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.