4

Is there a way in numpy to retrieve all items in an array except the item of the index provided.

 x = 
 array([[[4, 2, 3],
 [2, 0, 1],
 [1, 3, 4]],
 [[2, 1, 2],
 [3, 2, 3],
 [3, 4, 2]],
 [[2, 4, 1],
 [0, 2, 2],
 [4, 0, 0]]])

and by asking for

x[not 1,:,:] 

you will get

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

Thanks

asked Jan 3, 2012 at 12:30
3
  • For your simple example, you can use x[::2,:,:] Commented Jan 3, 2012 at 12:36
  • so what if x = np.random.ranint(10,size=(1000,3,3)) and I am trying to get a view of the matrix without the ith 3X3 matrix. Your approach cant be generalized :) Commented Jan 3, 2012 at 12:43
  • For the general case, I think indexing with a tuple would be easiest.. although maybe there is some numpy magic that I'm not aware of! Commented Jan 3, 2012 at 12:46

3 Answers 3

6
In [42]: x[np.arange(x.shape[0])!=1,:,:]
Out[42]: 
array([[[4, 2, 3],
 [2, 0, 1],
 [1, 3, 4]],
 [[2, 4, 1],
 [0, 2, 2],
 [4, 0, 0]]])
answered Jan 3, 2012 at 12:44

3 Comments

+1 This is just beautiful! With x[np.arange(x.shape[0])!=1,:,:] it would be even perfect :-)
Thanks for the improvement, eurimo.
I knew unutbu would chime in with a nice answer :) even x[np.arange(x.shape[0]) != 1] will work, the other dims will take : by default
2

Have you tried this?

a[(0,2), :, :]

Instead of blacklisting what you don't want to get, you can try to whitelist what you need.

If you need to blacklist anyway, you can do something like this:

a[[i for i in range(a.shape[0]) if i != 1], :, :]

Basically you just create a list with all possible indexes (range(a.shape[0])) and filter out those that you don't want to get displayed (if i != 1).

answered Jan 3, 2012 at 12:40

2 Comments

What if I have 1000 2D matrices ?? should it be (0,2,3,4,...).
@JustInTime I'm not sure I understand, but the [i for i in range(a.shape[0]) if i != 1] expression will let you create a mask for all the indexes you need except 1 regardless of number of matrices because of a.shape[0] usage.
2

This is quite a generic solution:

x[range(0,i)+range(i+1,x.shape[0]),:,:] 
answered Jan 3, 2012 at 12:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.