【问题标题】:Validate strings using regex in pandas在 pandas 中使用正则表达式验证字符串
【发布时间】:2017-12-23 18:48:54
【问题描述】:

我需要一点帮助。

我对 Python 还是很陌生(我使用与 Anaconda 捆绑在一起的 3.0 版),我想使用正则表达式来验证/返回仅包含符合条件的有效数字的列表(比如 11 位数字的 \d{11}) .我正在使用 Pandas 获取列表

df = pd.DataFrame(columns=['phoneNumber','count'], data=[
    ['08034303939',11],
    ['08034382919',11],
    ['0802329292',10],
    ['09039292921',11]])

当我使用

退回所有物品时
for row in df.iterrows(): # dataframe.iterrows() returns tuple
    print(row[1][0])

它返回所有没有正则表达式验证的项目,但是当我尝试用这个验证时

for row in df.iterrows(): # dataframe.iterrows() returns tuple
    print(re.compile(r"\d{11}").search(row[1][0]).group())

它返回一个属性错误(因为不匹配值的返回值为None。

我该如何解决这个问题,或者有更简单的方法吗?

【问题讨论】:

    标签: python regex string pandas dataframe


    【解决方案1】:

    如果要验证,可以使用str.match 并使用df.astype(bool) 转换为布尔掩码:

    x = df['phoneNumber'].str.match(r'\d{11}').astype(bool)
    x
    
    0     True
    1     True
    2    False
    3     True
    Name: phoneNumber, dtype: bool
    

    您可以使用布尔索引仅返回具有有效电话号码的行。

    df[x]
    
       phoneNumber  count
    0  08034303939     11
    1  08034382919     11
    3  09039292921     11
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多