0

I have this 2d array :

   import numpy as np

R = int(input("Enter the number of rows:")) //4
C = int(input("Enter the number of columns:")) //5

randnums= np.random.randint(1,100, size=(R,C))

print(randnums)
    [[98 25 33  9 41]
     [67 32 67 27 85]
     [38 79 52 40 58]
     [84 76 44  9  2]]

Now, i want to happen is that i will search an element and the output will be its column and rows example.

enter number to search : 40

Number 40 found in row 3 column 4

enter number : 100

number not found

something like this ? thanks in advance

4
  • Use nested loops over the row and column indexes. When you find the matching element, return the current indexes. Commented Jun 12, 2020 at 6:28
  • Does this answer your question? Finding indices of values in 2D numpy array Commented Jun 12, 2020 at 6:35
  • I understand, and thankyou for that @Barmar, i will update the question and next time wont be again like this. appologies im new here for asking Commented Jun 12, 2020 at 6:46
  • and also, this is my very first time trying to learn python. as in first time, im confuse about syntaxes thats why i asked. but then, yeah i will update. thanks again Mr @Barmar Commented Jun 12, 2020 at 6:59

3 Answers 3

1
l = [[98, 25, 33,  9, 41],
[67, 32, 67, 27, 85],
[38, 79, 52, 40, 58],
[84, 76, 44,  9,  2]]

def fnd(l,value):
    for i,v in enumerate(l):
        if value in v:
            return {'row':i+1,'col':v.index(value)+1}
    return {'row':-1,'col':-1}
print(fnd(l,40))
{'row': 3, 'col': 4}
Sign up to request clarification or add additional context in comments.

Comments

1

If the number of columns will be constant as shown in the example, you can search using below code.

a = [[98, 25, 33, 9, 41],
     [67, 32, 67, 27, 85],
     [38, 79, 52, 40, 58],
     [84, 76, 44, 9, 2]]
a_ind = [p[x] for p in a for x in range(len(p))] # Construct 1d array as index for a to search efficiently.


def find(x):
    return a_ind.index(x) // 5 + 1, a_ind.index(x) % 5 + 1 # Here 5 is the number of columns


print(find(98), find(58), find(40))

#Output
(1, 1) (3, 5) (3, 4)

Comments

1

You can use numpy.where function.

r = np.random.randint(1,10, size=(5,5))

# array([[6, 5, 3, 1, 8],
#        [3, 9, 7, 5, 6],
#        [6, 2, 5, 5, 8],
#        [1, 5, 1, 1, 1],
#        [1, 6, 5, 8, 6]])

s = np.where(r == 8)

# the first array is row indices, second is column indices
# (array([0, 2, 4], dtype=int64), array([4, 4, 3], dtype=int64))

s = np.array(np.where(r == 8)).T

# transpose to get 2d array of indices
# array([[0, 4],
#        [2, 4],
#        [4, 3]], dtype=int64)

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.