0

I'm using python 2.7.13, and I'm perplexed by a behavior that I'm seeing when using array slicing with numpy.

import numpy as np
a=np.array([1,1,2,3,4,5,6,7])
print a
print a[1:]
print a[1:] > 3

print np.where( a[1:]  > 1 )

I was expecting that I would see for the final output [2 3 4 5 6 7 8] i.e. the indices of the array that were found within the slice.

My goal was to apply the Boolean mask to all elements of the array except the first element. Then to grab value in the array that corresponded to the first 'True' value in the index array. Is this possible?

1
  • where just tells you where a[1:]>1 is True. It does nothing with a. Commented Aug 16, 2017 at 6:43

2 Answers 2

3

Your code is doing exactly what you want it to do. When you slice a[1:], you get np.array([1, 2, 3, 4, 5, 6, 7]). The output I got:

(array([1, 2, 3, 4, 5, 6], dtype=int64),)

is giving you the indices of 2, 3, 4, 5, 6, 7, in the slice of a you specified.

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

Comments

1

I guess this solves your problem:

import numpy as np
a=np.array([1,1,2,3,4,5,6,7])
b=a[1:]
print np.where( b  > 1 )

In your case, the print statement returns the element indices in the array a, while skipping the first elememnt. to get the indices in array a, print np.where(a>1) I hope this helps.

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.