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