Input − Assume, you have a Series,
0 apple 1 oranges 2 alpha 3 aroma 4 beta
Output − And, the result for elements start and endswith ‘a’.
2 alpha 3 aroma
Solution 1
Define a Series.
Create regular expression to check start and endswith ‘a’
r'^[a]$|^([a]).*\1$'
Create an empty list and set for loop and set if condition inside to check the pattern. It is defined below,
for i in data: if(re.search(exp, i)): ls.append(i)
Finally, check the series using isin().
Example
Let us see the following implementation to get a better understanding.
import pandas as pd import re l = ["apple","oranges","alpha","aroma","beta"] data = pd.Series(l) exp = r'^[a]$|^([a]).*\1$' ls = [] for i in data: if(re.search(exp, i)): ls.append(i) print(data[data.isin(ls)])
Output
2 alpha 3 aroma
Solution 2
Example
import pandas as pd import re l = ["apple","oranges","alpha","aroma","beta"] data = pd.Series(l) result = list(filter(lambda x:x.startswith('a') and x.endswith('a'),l)) print(data[data.isin(result)])
Output
2 alpha 3 aroma