3

I want to get the elements of a numpy array using an index array like so

import numpy 
a = numpy.arange(6)
ind = [2,3]

now, a[ind] gives me the 3rd and 4th element, but I actually want all the other elements of a. Is there a one line/ elegant way to do this?

3 Answers 3

4

There isn't a straightforward way I know of to get the complement of a set of integer indices. Boolean index negation is easy, which lets you do something like this:

In [100]: a=np.arange(6)

In [101]: ind=[2,3]

In [102]: cind=(a==a)

In [103]: cind[ind]=False

In [104]: a[cind]
Out[104]: array([0, 1, 4, 5])

But it isn't a one line solution.

Sign up to request clarification or add additional context in comments.

1 Comment

you can use np.ones(a.shape, 'bool') instead of (a==a)
1

maybe like this:

import numpy  
a = numpy.arange(6) 
ind = [1,3]
for x in range(6):
 if x not in ind: print a[x]

Comments

1

This has been suggested here before, but this is a list comprehension and therefore a oneliner:

numpy.array([a[i] for i in range(len(a)) if i not in ind])

results in

array([0, 1, 4, 5])

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.