【问题标题】:pandas: Validating data frame cells using regular expressionspandas:使用正则表达式验证数据框单元格
【发布时间】:2016-03-04 07:23:04
【问题描述】:

我有一个从 csv 文件读取的超过 50000 行的非索引数据框,如下所示:

John   Mullen  12/08/1993  Passw0rd
Lisa   Bush    06/12/1990  myPass12
Maria  Murphy  30/03/1989  qwErTyUi
Seth   Black   21/06/1991  LoveXmas

我想根据特定的正则表达式验证每一行的每个单元格:

  • 使用下面的PassRegex 验证密码
  • 使用下面的NameRegex 验证名字/姓氏
  • 等等……

然后将任何单元格未验证的行移动到新的数据框。

import re
PassRegex = re.compile(r"^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,50}$")
NameRegex = re.compile(r"^[a-zA-Z0-9\s\-]{2,80}$")

例如在这种情况下,下面的行不会使用 PassRegex 进行验证,所以我想将它们移动到单独的数据框:

Maria  Murphy  30/03/1989  qwErTyUi
Seth   Black   21/06/1991  LoveXmas

有没有一种方法可以在不逐行、逐个单元格地遍历整个数据帧的情况下做到这一点?

非常感谢任何帮助。

【问题讨论】:

    标签: python regex python-2.7 pandas


    【解决方案1】:

    您可以将正则表达式传递给str.contains

    In [36]:
    passRegex = r"^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,50}$"
    nameRegex = r"^[a-zA-Z0-9\s\-]{2,80}$"
    df[(df['password'].str.contains(passRegex, regex=True)) & (df['first'].str.contains(nameRegex, regex=True)) & (df['last'].str.contains(nameRegex, regex=True))]
    
    Out[36]:
      first    last         dob  password
    0  John  Mullen  12/08/1993  Passw0rd
    1  Lisa    Bush  06/12/1990  myPass12
    

    为了只保留感兴趣的行,这将为每个条件创建一个布尔掩码并将&and 一起使用,由于运算符优先级,您需要括号

    每个条件的输出:

    In [37]:
    df['password'].str.contains(passRegex, regex=True)
    
    Out[37]:
    0     True
    1     True
    2    False
    3    False
    Name: password, dtype: bool
    
    In [38]:
    df['first'].str.contains(nameRegex, regex=True)
    
    Out[38]:
    0    True
    1    True
    2    True
    3    True
    Name: first, dtype: bool
    
    In [39]:
    df['last'].str.contains(nameRegex, regex=True)
    
    Out[39]:
    0    True
    1    True
    2    True
    3    True
    Name: last, dtype: bool
    

    然后当我们组合它们时:

    In [40]:
    (df['password'].str.contains(passRegex, regex=True)) & (df['first'].str.contains(nameRegex, regex=True)) & (df['last'].str.contains(nameRegex, regex=True))
    
    Out[40]:
    0     True
    1     True
    2    False
    3    False
    dtype: bool
    

    【讨论】:

    • 嘿@EdChum,很抱歉这么晚才回答这个问题,但是如果我想从文本文件中获取这个正则表达式并在我的代码中使用它,那么我们该怎么做呢?用%s 替换对我不起作用:(
    • @ManasJani 请发布一个新问题,其中包含您的原始数据、重新创建 df 的代码、所需的输出以及您的尝试。通过 cmets 回答问题会适得其反
    • 前几天已经发过这个问题了,stackoverflow.com/questions/53711128/…
    猜你喜欢
    • 2011-11-06
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 2011-11-01
    相关资源
    最近更新 更多