gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:22:15 25 4
gpt4 key购买 nike

我想检查名为 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)

最佳答案

您可以在此处传递 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

关于python - Pandas:检查系列 A 中的单词是否以系列 B 中的一个单词结尾的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25668977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com