熊猫:检查A系列中的单词是否以B系列中的一个单词结尾的最快方法

seb*_*835 7 python performance pandas

我想检查一个系列中的单词是否以系列的strings一个单词结尾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])
Run Code Online (Sandbox Code Playgroud)

我已经提出了以下代码,但有没有更快或更多的熊猫风格的方式来做到这一点?

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)
Run Code Online (Sandbox Code Playgroud)

DSM*_*DSM 15

你可以endswith在这里传递一个元组(所以你不妨使用它而不是系列):

>>> 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
Run Code Online (Sandbox Code Playgroud)