Pandas: fastest way to check if words in series A end with one word in series B

I want to check if words in a series end with strings

one series word ending_strings

.

strings = Series(['om', 'foo_nom', 'nom', 'bar_foo', 'foo','blah'])
ending_strings = Series(['nom', 'foo'])
expected_results = Series([False, True, True, True, True, False])

      

I came up with the following code, but is there a faster or more pandas style way?

from pandas import Series

def ew(v):
    return strings.str.endswith(v) 
result = ending_strings.apply(ew).apply(sum).astype(bool)
result.equals(expected_results)

      

+3


source to share


1 answer


You can pass a endswith

tuple here (so you can use that instead of a series):



>>> strings = Series(['om', 'foo_nom', 'nom', 'bar_foo', 'foo','blah'])
>>> ending_strings = ("nom", "foo")
>>> strings.str.endswith(ending_strings)
0    False
1     True
2     True
3     True
4     True
5    False
dtype: bool

      

+7


source







All Articles