2

Given that, i have the below array:

 import numpy as np

 dt = np.array([1,2,3,4,5,2,1,3])

I can select the cells which has the value less than 3 by below code:

print(dt[dt<3])

But, how may i obtain the index of the selected cells?

my favorit result is:

[0,1,5,6]
Jeff
  • 7,767
  • 28
  • 85
  • 138

2 Answers2

4

try

x = np.array([1,2,3,4,5,2,1,3])
np.where(x<3)

output:

(array([0, 1, 5, 6], dtype=int64),)

you will get all index which are true.

Arjunsai
  • 176
  • 1
  • 7
0

I'm not sure that you need numpy for this.

lst = [1, 2, 3, 4, 5, 2, 1, 3]
indexes = [i for i, v in enumerate(lst) if v < 3]
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
  • is there any easier way? i try to avoide loops – Jeff Jul 06 '19 at 19:55
  • @Jeff, there's no way to avoid loops when you need to iterate over list. Also I want to mention that this is list comprehension, not a standard loop (but still loop). – Olvin Roght Jul 06 '19 at 19:57
  • I think what Jeff meant is a loop in Python. With numpy, the loop is in C, so it's much faster – Nakor Jul 06 '19 at 20:00
  • @Nakor, how much faster? 0.001% faster? If you're so sick to do optimization on loops, then just try to measure how much time it takes to initialize numpy. – Olvin Roght Jul 06 '19 at 20:01
  • I did actually. With a list of size 1M, your solution was 222ms, numpy was 8ms. So the answer is: 2700% faster in this case. And initialiation doesnt count depending on what you're working on. His post was maybe just an example for his true problem – Nakor Jul 06 '19 at 20:03