Skip to content
Advertisement

How to create a mask of substrings using np.where or list comprehensions?

I have two python lists of strings that I would like to compare. The first is my main list, containing a series of long codes. The second is a list of partial strings.

JavaScript

The desired result is a mask of list 1, populated by the substrings from list two. If no match is found, list3 can return 0, np.nan, ‘-‘, or similar. In other words, I’m looking for the following:

JavaScript

With help from folks in another thread, I was able to get close. However, these results return the values in list1, but I would like my result to return the matching substring from list2.

JavaScript

Advertisement

Answer

You may use:

JavaScript

Which yields

JavaScript

Your could even put it in a comprehension:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement