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]
1
  • If you want to use numpy, you could just do np.arange(len(dt))[dt<3]. Commented Jul 6, 2019 at 19:55

2 Answers 2

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.

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

Comments

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]

5 Comments

is there any easier way? i try to avoide loops
@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).
I think what Jeff meant is a loop in Python. With numpy, the loop is in C, so it's much faster
@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.
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.