Categories
Python Answers

How to test if a string contains one of the substrings in a list, in Python Pandas?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *