【问题标题】:Pandas: fastest way to check if words in Series A endswith one word of Series BPandas:检查 A 系列中的单词是否以 B 系列中的一个单词结尾的最快方法
【发布时间】:2014-09-05 01:31:51
【问题描述】:

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

【问题讨论】:

    标签: python performance pandas


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 2016-07-16
      • 2015-03-03
      • 2018-04-21
      • 2021-08-18
      相关资源
      最近更新 更多