【问题标题】:Pandas Regex: Separate name from string that starts with word or start of string, and ends in certain wordsPandas Regex:将名称与以单词或字符串开头并以某些单词结尾的字符串分开
【发布时间】:2021-04-29 22:43:16
【问题描述】:

我有一个熊猫系列,其中包含多行共享名称以及其他详细信息:

Netflix DIVIDEND
Apple Inc (All Sessions) COMM
Intel Corporation CONS
Correction Netflix Section 31 Fee

我正在尝试使用正则表达式来检索股票名称,我对此进行了展望:

transactions_df["Share Name"] = transactions_df["MarketName"].str.extract(r"(^.*?(?=DIVIDEND|\(All|CONS|COMM|Section))")

我唯一遇到的问题是行Correction Netflix Section 31 Fee,我的正则表达式将共享名设为Correction Netflix。我不想要“更正”这个词。

我需要我的正则表达式来检查字符串的开头或单词“Correction”。

我尝试了一些东西,例如以字符串字符 ^ 开头的 OR |。我还尝试向后看以检查 ^Correction 但错误说它们需要是恒定的长度。

r"((^|Correction ).*?(?=DIVIDEND|\(All|CONS|COMM|Section))"

给出一个错误; ValueError: Wrong number of items passed 2, placement implies 1。我是正则表达式的新手,所以我真的不知道这是什么意思。

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    您可以使用可选部分,而不是环视,使用匹配的捕获组:

    ^(?:Correction\s*)?(\S.*?)\s*(?:\([^()]*\)|DIVIDEND|All|CONS|COMM|Section)
    
    • ^ 字符串开始
    • (?:Correction\s*)?
    • (\S.*?)\s*组 1 中的捕获,匹配非空白字符和尽可能少的字符并匹配(不捕获)0+ 个空白字符
    • (?: 交替的非捕获组|
      • \([^()]*\) 匹配从 ()
      • |或者
      • DIVIDEND|All|CONS|COMM|Section匹配任意单词
    • )关闭群

    Regex demo

    data = ["Netflix DIVIDEND", "Apple Inc (All Sessions) COMM", "Intel Corporation CONS", "Correction Netflix Section 31 Fee"]
    pattern = r"^(?:Correction\s*)?(\S.*?)\s*(?:\([^()]*\)|DIVIDEND|All|CONS|COMM|Section)"
    transactions_df = pd.DataFrame(data, columns = ['MarketName'])
    transactions_df["Share Name"] = transactions_df["MarketName"].str.extract(pattern)
    print(transactions_df)
    

    输出

    0                   Netflix DIVIDEND            Netflix
    1      Apple Inc (All Sessions) COMM          Apple Inc
    2             Intel Corporation CONS  Intel Corporation
    3  Correction Netflix Section 31 Fee            Netflix
    

    【讨论】:

    • 谢谢你的作品!正则表达式令人困惑,我必须了解有关捕获组的更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多