【问题标题】:PANDAS Find the exact word and before word (multiple) in a column of string and append that, new column in python [duplicate]熊猫在一列字符串中找到确切的单词和之前的单词(多个)并将其附加到python中的新列[重复]
【发布时间】:2019-08-09 15:24:19
【问题描述】:

数据框如下所示

col_a
Python PY is a general purpose PY language

Programming PY language in Python PY 

Its easier to understand  PY

The syntax of the language is clean PY

此代码我已尝试实现此功能,但无法获得预期的输出。如果有任何帮助表示赞赏。

这是我使用正则表达式处理的以下代码:

df['col_a'].str.extract(r"([a-zA-Z'-]+\s+PY)\b")

期望的输出:

col_a                                       col_b_PY     
Python PY is a general purpose language         Python PY purpose PY
Programming PY language in Python PY            Python PY Programming PY     
Its easier to understand  PY                    understand PY 
The syntax of the language is clean PY          clean  PY

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    简单模式将提取所需的字符串:\w+\s+PY

    解释:\w+ 匹配一个或多个单词字符,然后\s+ 匹配一个或多个空格,后跟PY

    Demo

    【讨论】:

    • @Balu Weird,在演示中显示它可以根据需要进行捕获。只看演示。
    • @Balu,问题不在于正则表达式,而在于您关于捕获第二个模式的代码。
    • 只需使用.. df['col_a'].apply(lambda x: ' '.join(re.findall('\w+\s+PY',x))) @Balu跨度>
    • 正则表达式是正确的,但你需要将所有匹配项连接在一起
    • @Balu 如果您觉得有帮助,您可以选择对答案进行投票。
    【解决方案2】:

    使用@Michal 的正则表达式:

    import re
    def app(row):
        return ' '.join(re.findall(r'\w+\s+PY', row.col_a))
    
    df['col_b_PY'] = df.apply(app, axis=1)
    

    您需要连接应用函数中每一行的所有匹配项。也可以使用extractall 来做到这一点,但我发现这更简单直接。

    【讨论】:

      猜你喜欢
      • 2019-08-08
      • 1970-01-01
      • 2017-09-07
      • 1970-01-01
      • 2020-04-26
      • 2020-10-07
      • 2016-04-05
      • 1970-01-01
      • 2013-07-22
      相关资源
      最近更新 更多