Harish kumaar S
Harish kumaar S

Reputation: 23

how to check if vaules of a matrix and an array are equal in python

Given a matrix mat and an array arr, for each row of the matrix if elements of Column 1 are equal to the corresponding element of the array, then print the corresponding value of Column 2 of the matrix.

mat = np.array([['abc','A'],['def','B'],['ghi','C'],['jkl','D']])
arr = np.array(['abc','dfe','ghi','kjl'])

Upvotes: 2

Views: 1694

Answers (2)

Bunny Sumith
Bunny Sumith

Reputation: 1

Output should be `['A', 'C']``

So above code can be modified as

print(mat[np.where(mat[:,0]=arr)][:,1]
# output ['A' 'C']

Upvotes: 0

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

This can be solved via numpy.where.

Extract the first row of the matrix using mat[:,0], and compare it to arr using np.where(mat[:,0] == arr) to extract the indexes. and use those indexes to get the elements you want from mat


In [1]: import numpy as np 
   ...:  
   ...: mat = np.array([['abc','A'],['def','B'],['ghi','C'],['jkl','D']]) 
   ...:  
   ...: arr = np.array(['abc','dfe','ghi','kjl'])                                                                                                                                                       

In [2]: print(mat[np.where(mat[:,0] == arr)])                                                                                                                                                           
[['abc' 'A']
 ['ghi' 'C']]

Upvotes: 2

Related Questions