【问题标题】:Regex to remove specific parts of a string in a column dataframe python正则表达式删除列数据框python中字符串的特定部分
【发布时间】:2020-09-23 01:21:59
【问题描述】:

我正在使用包含地址的数据框,并且我想删除字符串的特定部分。比如像

并且我想删除字符串,因为将“REFERENCE:”和“reference:”放在句子的末尾。另外我想创建一个看起来像这样的新列(没有单词 REFERENCE:/reference: 和这些单词的下一个字母)你能帮我在 Regex 中做吗? 我希望它的新列看起来像这样:

【问题讨论】:

  • 你应该把你拥有的代码和输出放在文本中,这样我们就可以轻松地处理它们。

标签: python regex string dataframe python-re


【解决方案1】:

您可以使用一些正则表达式来获得所需的结果。

df = pd.DataFrame({"address": ["Street Pases de la Reforma #200 REFERENCE: Green house", "Street Carranza #300 12 & 13 REFERENCE: There is a tree"]})

df.address.str.findall(r".+?(?=REFERENCE)").explode()

0    Street Pases de la Reforma #200 
1       Street Carranza #300 12 & 13

正则表达式模式的解释:

.+? matches any character (except for line terminators)
+? Quantifier — Matches between one and unlimited times, as few times as possible, expanding as needed (lazy)
Positive Lookahead (?=REFERENCE)

【讨论】:

    【解决方案2】:

    正则表达式应如下所示:

    import re
    
    discard_re = re.compile('(reference:.*)', re.IGNORECASE | re.MULTILINE)
    

    然后您可以添加新列:

    df['address_new'] = df.addresses.map(lambda x: discard_re.sub('', x))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2021-11-25
      • 2021-08-30
      • 2022-01-27
      相关资源
      最近更新 更多