2

I am new to NumPy. I have a 2-D NumPy array containing floating point values. I wish to get the index of those elements which are greater than 70 % of a certain value, say t ,in the entire matrix.

output = [(1,2),(4,7),(7,1)] meaning arr[1][2], arr[4][7] and arr[7][1] have values greater than 70% of t

Using 2 loops to get job done is a fairly uncomplicated way. What is the most Pythonic way of getting it done (list comprehension etc.) ? Please point out any duplicates. Thanks !

4
  • 1
    Numpy's where sounds relevant here, give it a look. Commented May 31, 2015 at 0:40
  • Give the rest of that sample case, including your loops. Any by the way, for numpy we normally index: arr[1,2], not arr[1][2]. Commented May 31, 2015 at 0:52
  • @hpaulj Sorry, did not get your point. Sample case as in ? I just have a 2-D array I wish to traverse. Commented May 31, 2015 at 1:01
  • Note: frequently, computing the actual indices is unnecessary overhead. Most calls to where I see around here can simply be removed without affecting the program's behavior, and the code will run faster. Commented May 31, 2015 at 1:24

1 Answer 1

3

An example:

In [76]: arr=np.arange(20, dtype=float).reshape(4,5)

In [77]: arr
Out[77]: 
array([[  0.,   1.,   2.,   3.,   4.],
       [  5.,   6.,   7.,   8.,   9.],
       [ 10.,  11.,  12.,  13.,  14.],
       [ 15.,  16.,  17.,  18.,  19.]])

A boolean index that can select values from the array

In [79]: arr>15
Out[79]: 
array([[False, False, False, False, False],
       [False, False, False, False, False],
       [False, False, False, False, False],
       [False,  True,  True,  True,  True]], dtype=bool)

In [80]: arr[arr>15]
Out[80]: array([ 16.,  17.,  18.,  19.])

Indexes where the condition is true, which can also be used to select elements

In [81]: I=np.nonzero(arr>15)

In [82]: I
Out[82]: (array([3, 3, 3, 3], dtype=int32), array([1, 2, 3, 4], dtype=int32))

In [83]: arr[I]
Out[83]: array([ 16.,  17.,  18.,  19.])

Or turn the index tuple into a list of pairs

In [84]: list(zip(*I))
Out[84]: [(3, 1), (3, 2), (3, 3), (3, 4)]

In [87]: [arr[j] for j in zip(*I)]
Out[87]: [16.0, 17.0, 18.0, 19.0]

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.