【问题标题】:How to drop and keep only certain non alphanumeric characters?如何删除并仅保留某些非字母数字字符?
【发布时间】:2019-06-21 16:55:25
【问题描述】:

我的 df 看起来像这样:

email                                    id
{'email': ['test@test.com']}           {'id': ['123abc_d456_789_fgh']}

当我像这样删除非字母数字字符时:

df.email = df.email.str.replace('[^a-zA-Z]', '')
df.email = df.email.str.replace('email', '')


df.id = df.id.str.replace('[^a-zA-Z]', '')
df.id = df.id.str.replace('id', '')

列如下所示:

email                    id
testtestcom              123abcd456789fgh

如何告诉代码不要在方括号中删除任何内容,而是将所有非字母数字字符放在方括号外?

新的 df 应该是这样的:

email                        id
test@test.com                123abc_d456_789_fgh

【问题讨论】:

    标签: python-3.x pandas replace non-alphanumeric


    【解决方案1】:

    这是硬编码的,但有效:

    df.email = df.email.str.replace(".+\['|'].+", '')
    df.id = df.id.str.replace(".+\['|'].+", '')
    
    >>> 'test@test.com'
    >>> '123abc_d456_789_fgh'
    

    【讨论】:

      【解决方案2】:

      根据 cmets,您可能会做的是捕获捕获组中方括号之间的内容。

      在替换中使用第一个捕获组。

      \{'[^']+':\s*\['([^][]+)'\]}
      

      这将匹配

      • \{匹配{
      • '[^']+'匹配',然后不匹配' 1+次
      • : 字面匹配
      • \s*\[' 匹配 0+ 次空格字符,然后匹配 [
      • ([^][]+) 捕获组,不匹配 []
      • '\]匹配]
      • } 字面匹配

      Regex demo | Python demo

      【讨论】:

      • df.email = df.email.str.replace('(\[[^][]+\])|[^a-zA-Z]','') 删除除 email 之外的所有内容
      • 您的问题是How do I tell the code to not drop anything in the square brackets but drop all non alpha numeric characters outside the brackets? 电子邮件在方括号内。
      • email 绝对不在方括号中。它在波浪形的括号内没有?
      • 我以为你想保留电子邮件并在单独的替换中这样做,因为你使用了 [^a-zA-Z]` 如果你想删除所有,你可以试试(\[[^][]+\])|.@987654323 @ 在这种情况下,为什么不只匹配这些值? \[[^][]+\]demo
      • 以上行删除了所有内容。我只想保留列中的电子邮件地址和 ID,就是这样。
      猜你喜欢
      • 2014-04-11
      • 2019-07-31
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多