Python np where , variable as array index, tuple

Question:

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
`
Asked By: toto45

||

Answers:

So you want to lookup a key and get a value?

It feels like you need to use dict!

>>> ar=[[11,'a'],[12,'b'],[13,'c'],[14,'d']]
>>> d = dict([(k,v) for v,k in ar])
>>> d
{'a': 11, 'b': 12, 'c': 13, 'd': 14}
>>> d['d']
14
Answered By: Nathan McCoy

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]
Answered By: Andreas

I didn’t know about np.where! It’s docstring mentions using nonzero directly, so here’s a code snippet that uses that to print the rows that match your requirement: note I add another row with 'd' to show it works for the general case where you want multiple rows matching the condition:

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

rows = arr[(arr=='d').nonzero()[0], :]
# array([['14', 'd'],
#        ['16', 'd']], dtype='<U21')

This works because nonzero (or where) returns a tuple of row/column indexes of the match. So we just use the first entry in the tuple (an array of row indexes) to index the array row-wise and ask Numpy for all columns (:). This makes the code a bit fragile if you move to 3D or higher dimensions, so beware.

This is assuming you really do intend to use Numpy! Dict is better for many reasons.

Answered By: Ahmed Fasih
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.