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?

rioZg
  • 530
  • 1
  • 6
  • 17
  • 3
    `np.where(histarr == 1)[0]` or `np.flatnonzero(histarr == 1)`? – Divakar May 27 '20 at 07:45
  • Does this answer your question? [output of numpy.where(condition) is not an array, but a tuple of arrays: why?](https://stackoverflow.com/questions/33747908/output-of-numpy-wherecondition-is-not-an-array-but-a-tuple-of-arrays-why) – StupidWolf May 27 '20 at 08: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. – rioZg May 27 '20 at 08:14
  • I still do not get how I get the result that I get in my question. – rioZg May 27 '20 at 08: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. – norok2 May 27 '20 at 08:30

1 Answers1

1

You should be able to do it in one line:

np.where(histarr == 1)[0]
CHRD
  • 1,917
  • 1
  • 15
  • 38
  • Thanks that works NOW magically. I tried that before and got some error that I can not reproduce anymore. – rioZg May 27 '20 at 08:14