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

标签 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])

我想出了以下代码,但是否有更快或更 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/

相关文章:

php - 在处理来自 ffmpeg 的输入时将数据推送到网络浏览器

php - PDO 会关闭持久连接吗?

python - Pandas DataFrame 样式器 - 如何将 pandas 数据框样式设置为 excel 表?

python pandas df 合并多索引的一部分

python - 调用一个 python 函数,该函数接受 MATLAB 函数句柄作为来自 matlab 的参数

python - 在 Django 商店中本地化价格的正确方法是什么?

python - 如何在 python 中使 for 循环更易于理解?

java - 什么是【Full GC(分配失败)

Javascript 对象与原语

python - Groupby 类和计数特征中的缺失值