【问题标题】:Regex, Pandas and flagging rows正则表达式、熊猫和标记行
【发布时间】:2021-07-20 04:43:13
【问题描述】:

我正在尝试标记任何包含用户定义的“不正确”字符的记录。在这种情况下,记录二 (2) 应作为无效记录返回,但我似乎捕获了记录 1 或 3。这些将被视为“正确”。 关于为什么这些被标记而不是“错误记录”的任何建议?

import pandas as pd
import numpy as np
import re

data = {'HOME1': ['123 Main St', '567\ Country Road', 'PO Box 900']}
dft = pd.DataFrame(data)

from itertools import chain
chars =[]
acceptable = [x for x in chain(range(48,58),range(32,33), range(65,91), range(97,123))]
for ch in acceptable:
    chars.append(chr(ch))

reg_list = map(re.compile,chars)

for x in dft['HOME1']:
    print(x)
    if any(re.match(x) for re in reg_list):
        conditions = [dft['HOME1'].apply(lambda x: x)!=x, dft['HOME1'].apply(lambda x: x)==x]
        choices = [0,1]
        dft['NonValidHOME1'] = np.select(conditions,choices,default=0)

try:
    print(dft.groupby(['NonValidHOME1'])[['HOME1']].filter(lambda x: len(x) ==1).agg(lambda x: x.tolist()))
except:
    print("no invalid Home1")


【问题讨论】:

  • 我认为您需要删除 reg_list = map(re.compile,chars) 并将 if any(re.match(x) for re in reg_list): 替换为 if any(c in x for c in chars): (如果 x 是一个字符串)。如果您只是从字符串中的列表中检查单个字符,则不需要正则表达式。

标签: python regex pandas dataframe


【解决方案1】:
for x in dft['HOME1']:
for c in x:
    if c not in chars:
        print(c,x)
        conditions = [dft['HOME1'].apply(lambda x: x)==x, dft['HOME1'].apply(lambda x: x)!=x]
        choices = [1,0]
        dft['NonValidHOME1'] = np.select(conditions,choices,default=0)

#[print(c) for x in dft['HOME1'] for c in x if c not in chars]

        

感谢您的评论。这让我走上了一条“更好”的道路,或者至少让我找到了答案。

【讨论】:

    猜你喜欢
    • 2015-11-18
    • 2018-04-30
    • 2016-05-12
    • 2017-06-18
    • 2016-12-31
    • 2021-08-22
    • 1970-01-01
    • 2021-03-06
    相关资源
    最近更新 更多