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
`

>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]

Leave a Reply