How to use numpy.where() to get elements from array depend on condition expression in Python

3 Answers

0 votes
import numpy as np

arr = np.array([5, 6, 21, 9, 12, 23, 35, 26, 47, 58, 14, 68, 77, 80, 99])
 
result = np.where((arr > 10) & (arr < 30))
 
if len(result) > 0:
    print(result)
else:
    print('Not Found')
 

# arr[2] = 21
# arr[4] = 12
# arr[5] = 23 
# arr[7] = 26
# arr[10] = 14

'''
run:
 
(array([ 2,  4,  5,  7, 10]),)

'''

 



answered Feb 6, 2020 by avibootz
0 votes
import numpy as np

arr = np.array([5, 6, 21, 9, 12, 23, 35, 26, 47, 58, 14, 68, 77, 80, 99])
 
result = np.where((arr > 10) & (arr < 30))
 
if len(result) > 0:
    for item in result:
        print(arr[item])
else:
    print('Not Found')
 

# arr[2] = 21
# arr[4] = 12
# arr[5] = 23 
# arr[7] = 26
# arr[10] = 14

'''
run:
 
[21 12 23 26 14]

'''

 



answered Feb 6, 2020 by avibootz
0 votes
import numpy as np

arr = np.array([5, 6, 21, 9, 12, 23, 35, 26, 47, 58, 14, 68, 77, 80, 99])
 
result = np.where((arr > 10) & (arr < 30))
 
if len(result) > 0:
    for item in result:
        for i in item:
          print(arr[i])
else:
    print('Not Found')
 

# arr[2] = 21
# arr[4] = 12
# arr[5] = 23 
# arr[7] = 26
# arr[10] = 14

'''
run:
 
21
12
23
26
14

'''

 



answered Feb 6, 2020 by avibootz
...