1

Let's suppose a and b are given as below:-

a = np.arange(5)
b = [0,1,2]

What I want is that for indices excluding those in b ,values in a should be equal to -1. So in the above case a will be equal to

a = array([0, 1, 2, -1, -1])

There is a method which I am aware of i.e.

a[list(set(a)-set(b))] = -1

but takes too much time, and leads to too much complexity when actually writing the code. As always I am looking out for better methods than the above one. Feel free to use any tools required. Another example (just in case):- if

a = np.arange(12)
b = [3,5,6]

Then what I really want is a = array([-1, -1, -1, 3, -1, 5, 6, -1, -1, -1, -1, -1]) P.S. Don't worry a will always be of the form np.arange(int) and no value of b exceeds the length of a

2 Answers 2

3

Well if the object is to create a range of values that are either the same as their index or -1 then it might be simpler to start with all -1 and add the data you want rather than the other way around.

>>> a = np.full(12, -1, dtype=int)
>>> b = [3, 5, 6]
>>> a[b] = b
>>> a
array([-1, -1, -1,  3, -1,  5,  6, -1, -1, -1, -1, -1])
Sign up to request clarification or add additional context in comments.

Comments

3
>>> a = np.arange(12)
>>> b = [3,5,6]
>>> a[~np.in1d(np.arange(len(a)), b)] = -1
>>> a
array([-1, -1, -1,  3, -1,  5,  6, -1, -1, -1, -1, -1])

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.