Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python np where , variable as array index, tuple

I want to search a value in a 2d array and get the value of the correspondent "pair"
in this example i want to search for ‘d’ and get ’14’.
I did try with np location with no success and i finished with this crap code, someone else has a smarter solution?

`

import numpy as np

ar=[[11,'a'],[12,'b'],[13,'c'],[14,'d']]
arr = np.array(ar)
x = np.where(arr == 'd')

print(x) 



print("x[0]:"+str(x[0])) 

print("x[1]:"+str(x[1])) 


a = str(x[0]).replace("[", "")
a = a.replace("]", "")
a = int (a)
print(a)

b = str(x[1]).replace("[", "")
b = b.replace("]", "")
b = int (b) -1
print(b)

print(ar[a][b]) 
#got 14
`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a dict, simple and straight forward:

dct = {k:v for v,k in ar}
dct['d']

If you are hell bent on using np.where, then you can use this:

import numpy as np

ar = np.array([[11,'a'],[12,'b'],[13,'c'],[14,'d']])
i = np.where(ar[:,1] == 'd')[0][0]
result = ar[i, 0]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading