Anders
Anders

Reputation: 99

Find string elements in matrix from list

I want to search for string values that I have in a n x n matrix to see if they exist in a list. The output should be a n x n matrix with boolean True or False depending if the string was found. The matrix and the list look like this:

matrix = [['aa', 'ba', 'ca'], ['ab', 'bb', 'cb'], ['ac', 'bc', 'cc']]
list = ['ba','cb','dg'] 

I have this code:

matrixFound = [[for x in matrix] for y in matrix]

and I would need to somehow include this statement elementwise:

matrix in list

The output should be a matrix like this:

[[False,True,False],[False,False,True],[False,False,False]]

I was thinking of using map or lambda to solve this but cannot get the coding right. How should this be done? Regular python or numpy could be used.

Upvotes: 1

Views: 545

Answers (3)

Antilos
Antilos

Reputation: 53

Here's the code you are looking for if you want to use list comprehension.
matrixFound = [[x in list for x in y] for y in matrix]
It simulates nested loop where the outer comprehension chooses a column from matrix, and the inner one checks whether the elements are in list

Upvotes: 1

oppressionslayer
oppressionslayer

Reputation: 7204

You can use numpy's isin:

np.isin(matrix,list2)                                                                                                                                                               

# array([[False,  True, False],
#       [False, False,  True],
#       [False, False, False]])

Upvotes: 2

Wolph
Wolph

Reputation: 80021

With numpy it's absolutely trivial:

In [1]: import numpy

In [2]: matrix = numpy.array([['aa', 'ba', 'ca'], ['ab', 'bb', 'cb'], ['ac', 'bc', 'cc']])

In [3]: matrix == 'cb'
Out[3]:
array([[False, False, False],
       [False, False,  True],
       [False, False, False]], dtype=bool)

In [4]: search = ['ba','cb','dg']

In [5]: result = numpy.zeros(matrix.shape, dtype='bool')

In [6]: result
Out[6]:
array([[False, False, False],
       [False, False, False],
       [False, False, False]], dtype=bool)

In [7]: for s in search:
   ...:     result |= matrix == s
   ...:

In [8]: result
Out[8]:
array([[False,  True, False],
       [False, False,  True],
       [False, False, False]], dtype=bool)

Upvotes: 1

Related Questions