代码之家  ›  专栏  ›  技术社区  ›  Ryan

如何计算数据帧中正则表达式子字符串的匹配数,并将其作为新特性应用?

  •  0
  • Ryan  · 技术社区  · 6 年前

    https 在字符串内 str ,我可以做: str.count("https")

    但如何将其应用于数据帧的每一行?

    Label    Text
    0        Lorem ipsum dolor sit amet 😀
    1        Quis https://url.com/a nunc https://g.co/b elit 😀
    0        Donec https://url.com/c interdum libero,
    0        Consectetur convallis inbox.gmail.com/d auctor.
    1        Praesent 😡 semper magna lorem
    

    Label    Text                                             count_https
    0        Lorem ipsum dolor sit amet 😀                       0
    1        Quis https://url.com/a nunc https://g.co/b elit 😀  2
    0        Donec https://url.com/c interdum libero,            1
    0        Consectetur convallis inbox.gmail.com/d auctor.     0
    1        Praesent 😡 semper magna lorem                      0
    

    下面是我最近一次尝试使用 .find("https") :

    df.apply(lambda x: len([w for w in str(x).split() if w.find("https") != -1()]))
    

    TypeError: 'int' object is not callable
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   mad_    6 年前

    你可以用 count 但你还是想用lambda然后你就可以用 re

    import re
    df.apply(lambda x: len(re.findall('https',str(x))))
    

    在这种情况下,可以调用-1()来更正您的解决方案int变量,而不是检查索引位置,该位置仅为-1

    df.apply(lambda x: len([w for w in str(x).split() if w.find("https") != -1]))
    
        2
  •  2
  •   DeepSpace    6 年前

    不知道是不是错了,但是 -1()

    无论如何,有一个更好的方法来实现你想要做的事情。可以使用矢量化 count . 矢量化操作几乎总是比 apply

    df['count_https'] = df['Text'].str.count('https')