1

I have the following numpy array named histarr with the shape 1, 13

array([0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0], dtype=uint32)

I want to get an array that gives me positions where 1's are, hence I used np.where

where_are_ones_arr = np.where(histarr == 1)

The output is:

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

I was confused for a while but than I checked the type and I realized that where_are_ones_arr is not an array but it is actually a tuple, so if I wanted to get an array I used:

where_are_ones_arr[0]

Result:

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

Now that is all fine but I found it unbelievable that I cannot get that in one line, so I looked around and tried:

where_are_ones_give_me_only_array = histarr[np.where(histarr == 1)]

But it spits out:

array([1, 1, 1, 1, 1], dtype=uint32)

Which is not what I want and what I can explain? What is it that I do not get?

5
  • 3
    np.where(histarr == 1)[0] or np.flatnonzero(histarr == 1)? Commented May 27, 2020 at 7:45
  • Does this answer your question? output of numpy.where(condition) is not an array, but a tuple of arrays: why? Commented May 27, 2020 at 8:00
  • Thanks Divakar, that works. @StupidWolf I read that answer and an answer from paulj line 280 where he uses technique that I tried to reproduce in my question does not work for me. Commented May 27, 2020 at 8:14
  • I still do not get how I get the result that I get in my question. Commented May 27, 2020 at 8:17
  • Also: np.where() with only one argument is just calling under the hood just np.nonzero(), so calling np.nonzero() directly should be preferred. Commented May 27, 2020 at 8:30

1 Answer 1

1

You should be able to do it in one line:

np.where(histarr == 1)[0]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that works NOW magically. I tried that before and got some error that I can not reproduce anymore.

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.