user366121
user366121

Reputation: 3271

python matrix search

If I have the following matrix:

import numpy

ar = numpy.array((('0','1','2','3'), ('1','a','b','b'), ('2','b','c','d')), str)
print(ar)

Output:

[['0' '1' '2' '3']
 ['1' 'a' 'b' 'b']
 ['2' 'b' 'c' 'd']]

And I want to get the value where the condition for row and column is met. The header row are the columns (could be strings) and the first column on the left are all rows (could be strings). So if I have '2' for column and '2' for row I would get 'c'. I don't know 'c' yet only the values for rows and columns. How would I do that?

Upvotes: 1

Views: 6851

Answers (3)

yprez
yprez

Reputation: 15134

If you mean searching for 'c':

numpy.where(ar == 'c')

Upvotes: 2

lbolla
lbolla

Reputation: 5411

You can use numpy.where:

In [7]: numpy.where(ar == 'c')
Out[7]: (array([2]), array([2]))

and:

In [8]: ar[numpy.where(ar == 'c')]
Out[8]: 
array(['c'], 
      dtype='|S1')

Upvotes: 3

Paul
Paul

Reputation: 21975

ar = [['0', '1', '2', '3'],
 ['1', 'a', 'b', 'b'],
 ['2', 'b', 'c', 'd']]

print(ar[2][2])

The above is just for accessing the 'c' in column 2, row 2, if you want to access a whole column you would have to:

for i in range(0, 3):
    print(ar[2][i])

Upvotes: 1

Related Questions