This question already has an answer here:
Is there any function that would be the equivalent of a combination of df.isin()
and df[col].str.contains()
?
For example, say I have the series
s = pd.Series(['cat','hat','dog','fog','pet'])
, and I want to find all places where s
contains any of ['og', 'at']
, I would want to get everything but pet.
I have a solution, but it's rather inelegant:
searchfor = ['og', 'at']
found = [s.str.contains(x) for x in searchfor]
result = pd.DataFrame[found]
result.any()
Is there a better way to do this?
One option is just to use the regex
|
character to try to match each of the substrings in the words in your Seriess
(still usingstr.contains
).You can construct the regex by joining the words in
searchfor
with|
:As @AndyHayden noted in the comments below, take care if your substrings have special characters such as
$
and^
which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.You can make your list of substrings safer by escaping non-alphanumeric characters with
re.escape
:The strings with in this new list will match each character literally when used with
str.contains
.You can use
str.contains
alone with a regex pattern usingOR (|)
:Or you could add the series to a
dataframe
then usestr.contains
:Output: