0

I have two python ndarrays p and q as follows:

import numpy as np
p = np.array([1.        , 1.        , 0.1862802 , 0.19957115, 0.18623812,
       0.1802321 , 0.17464815, 0.16460853, 0.1487719 , 0.12968006,
       0.10464501, 0.07183418, 0.00124706, 0.27353592, 0.81713212,
       0.23720725, 0.21802175, 0.21959138, 0.22401754, 0.22662527,
       0.22777369, 0.23269387, 0.23293132, 0.23374038, 0.24089565,
       0.19958937, 0.23910928, 0.24252447])

q = np.array([[ 1.        ,  1.        ],
       [-0.357316  ,  0.1862802 ],
       [-0.34402505,  0.19957115],
       [-0.35735808,  0.18623812],
       [-0.36336411,  0.1802321 ],
       [-0.36894805,  0.17464815],
       [-0.37898767,  0.16460853],
       [-0.3948243 ,  0.1487719 ],
       [-0.41391615,  0.12968006],
       [-0.4389512 ,  0.10464501],
       [-0.47176202,  0.07183418],
       [-0.54234915,  0.00124706],
       [ 0.27353592,  0.81713212],
       [-0.30638895,  0.23720725],
       [-0.32557445,  0.21802175],
       [-0.32400482,  0.21959138],
       [-0.31957866,  0.22401754],
       [-0.31697093,  0.22662527],
       [-0.31582252,  0.22777369],
       [-0.31090234,  0.23269387],
       [-0.31066488,  0.23293132],
       [-0.30985582,  0.23374038],
       [-0.30270055,  0.24089565],
       [-0.34400684,  0.19958937],
       [-0.30448692,  0.23910928],
       [-0.30107173,  0.24252447]])

I want to get (a) all the values in p where first value of corresponding tuple in q is >0 and (b) the index of all those values in p

2 Answers 2

1

Use np.where:

idx = np.where(q[:,0]>0)

print(idx, p[idx])

Output:

(array([ 0, 12]),) [1.         0.00124706]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @QuangHoang. However, not clear why idx in idx = np.where(q[:,0]>0) is a tuple of ndarray and not just instance of ndarray
1

Obtaining the values in p whose corresponding tuple has the first value > 0:

idx = np.where(q[:,0]>0)
p[idx] 
##output [1.   0.00124706] 

Finding the indices of these values in p

for val in p[idx]:
        print(val, "index", np.where(p == val))
##output
1.0 index array([0, 1]) # 1.0 appears twice in p
0.00124706 index array([12])

Comments

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.