1

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
`
3
  • is there any reason you are not using a dictionary for this? Commented Feb 9, 2023 at 17:12
  • why are you using a numpy array for this data? Commented Feb 9, 2023 at 17:13
  • as an aside, instead of converting to a str then doing a bunch of string mangling and returning to an int, you can just do x[0][0] Commented Feb 9, 2023 at 17:14

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

no need to create a list and then convert it to dict, just create the dict directly: {k:v for v,k in ar}
0

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]

3 Comments

this works, nice, thanks a lot. I dont know dict, i did this a python selenium bot to sync Wifi client monitoring with a spreadsheet on google, the monitoring tools just gives me the mac addr and not the client name so i have to make something to match this mac addr to a name.
@toto45 two small tips, (1) Google has a nice Google Sheets API that you might be able to use to write to a spreadsheet instead of Selenium/webdriver/Puppeteer/Playwright. (2) Pandas is also the champion of data wrangling, and I like to use it everywhere, even small tiny projects like this because small tiny projects tend to grow to bigger projects and make me wish I'd used Pandas from the start. But Pandas has a learning curve so in a pinch, dict/numpy will do.
I use google script too, to send me alert/mail but the wifi controler is inside my network not accessible from outside, i dont want to open a public ip (with port forwarding or stuff) just for this. I dont know why 'i' return just what i wanna (a number int), probably an optional argument in the where
0

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.

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.