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

发布于 2021-01-29 14:57:28

我想检查命名为Series的单词是否以Series的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])

我想出了以下代码,但是有没有更快或更更多的熊猫风格方式呢?

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)
关注者
0
被浏览
67
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以endswith在此处传递一个元组(因此也可以使用它代替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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看