0

I have two arrays as follows:

e = np.array([True, False, True, True])    
f = np.array([True, False, False, True])

I want to get the index i where e[i] and f[i] == True.

The expected output for the above will be:

[0,3] since e[0] == True and f[0] == True; e[3] and f[3] ==True

There may be more of such matches, so I need a list of all of the indices which satisfy the above condition.

I tried to find the list of matching values by doing this:

list(e&f)
Out[474]:
[True, False, False, True]

To get the index, I thought I could use .index(True) of list. But it doesn't work or just gives output as 0. Maybe only giving the first index and not all.

Finally, I need the 1 added to each element of output so instead of [0,3] output should be [1,4] but this is easy I can do that if I get the indices,

2
  • 4
    You've asked several questions about searching numpy arrays. Aren't you learning general principles from the answers? It seems like you're just giving us your entire homework assignment and asking us to do it for you. Commented Jun 23, 2016 at 0:39
  • No there is no homework. I am working on some work. I do know general principle of numpy array. But my understanding says to get an index we can use .index function of list. but it gives only one value Commented Jun 23, 2016 at 0:40

4 Answers 4

3

Take a look at numpy.where in the docs

np.where(e&f)[0]

Outputs:

 array([0, 3])
Sign up to request clarification or add additional context in comments.

1 Comment

np.where(e&f)[0]+1 returns the array with 1-based indices.
1

You can just use a list comprehension to pick them out:

>>> e = np.array([True, False, True, True])    
>>> f = np.array([True, False, False, True])
>>> [i for i,v in enumerate(e&f, 1) if v]
[1, 4]

Using enumerate() you can specify the initial index, in this case 1.

1 Comment

@Baktaawar: you can use enumerate(), although there is probably a better numpy specific way to do it.
1

or simply this

np.where(e&f)

1 Comment

Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge.
1

Something else if you don't want to be dependent on numpy:

e=[True, False, True, True]
f=[True, False, False, True]

for idx, val in enumerate(e):
  if cmp(e[idx], f[idx]) is 0:
    print idx+1, val

1 Comment

Thanks Andy for fixing my copy&paste issue :D

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.