Pandas:检查Series A中的单词是否以Series B中的单词结尾的最快方法

8 投票
1 回答
2870 浏览
提问于 2025-04-19 20:15

我想检查一个叫做 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])

我写了下面的代码,但想知道有没有更快或者更符合 pandas 风格的方法来实现这个功能?

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)

1 个回答

17

你可以在这里给 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

撰写回答