Sometimes, we want to test if a string contains one of the substrings in a list.
In this article, we’ll look at how to test if a string contains one of the substrings in a list.
How to test if a string contains one of the substrings in a list, in Python Pandas?
To test if a string contains one of the substrings in a list, in Python Pandas, we call str.contains
.
For instance, we write
s = pd.Series(['cat','hat','dog','fog','pet'])
df = pd.DataFrame(s)
df[s.str.contains('og|at')]
to call s.str.contains
with with a regex pattern string to return the items in data frame df
that has the matched values.
Conclusion
To test if a string contains one of the substrings in a list, in Python Pandas, we call str.contains
.