Pandas series substring starts and ends with letter

Viewed 125

I have a large pandas series containing approximately half a million rows of this form:

pd.Series(['Lorem ipsum dolor sit amet',
            'consectetur adipiscing elit',
            'quis euismod mi, id venenatis urna',
            'curabitur vel augue viverra diam imperdiet laoreet'])

and I would like to filter the series by words that start and end with a specific letter. For example, if start letter is 'l' and end letter is 'm', then I want to include rows that have 'lorem' as substrings, or rather '^l.*m$'.

So I need to split my string into substring and do .str.contains('^l.*m$'), however I don't know of an optimised way to do this.

1 Answers

You can use word boundaries matching from L to m \bL\w*m\b and in between match 0 or more word characters.

import pandas as pd

s = pd.Series(['Lorem ipsum dolor sit amet',
           'consectetur adipiscing elit',
           'quis euismod mi, id venenatis urna',
           'curabitur vel augue viverra diam imperdiet laoreet'])
s = s.str.contains(pat = r'\bL\w*m\b', regex = True)
print(s)

Output

0     True
1    False
2    False
3    False
dtype: bool
Related