3

I want to get the c array as result, but I don't know how:

import numpy as np
a = xrange(10)
b = np.array([3,2,1,9])

c is made of elements of a that are not in b:

c = np.array([0,4,5,6,7,8])
1
  • What is np.xrange? You mean np.arange? Commented Dec 31, 2011 at 13:05

2 Answers 2

10

Perhaps a more straightforward solution is the following:

import numpy as np
a = xrange(10)
b = np.array([3,2,1,9])

c = np.setdiff1d(a,b)

Which results in:

In [7]: c
Out[7]: array([0, 4, 5, 6, 7, 8])

You can find all of the set-like operations for numpy arrays in the documentation: http://docs.scipy.org/doc/numpy/reference/routines.set.html

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

Comments

3
import numpy as np
a = np.arange(10)
b = np.array([3,2,1,9])

np.array(sorted(set(a) - set(b)))
# array([0, 4, 5, 6, 7, 8])

UPDATE: works with a = xrange(10) too.

2 Comments

This is inefficient for large arrays. @JoshAdel's answer is a better way.
I would just say that having played around with the timings, @eumiro's solution is surprisingly efficient for a pretty wide range of array sizes. I would recommend benchmarking for your particular case to see which is better, also noting that np.setdiff1d has an option if both arrays contain only unique values, which can speed things up.

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.