python - 正则表达式、熊猫和标记行
问题描述
我正在尝试标记任何包含用户定义的“不正确”字符的记录。在这种情况下,记录二 (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")
解决方案
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]
感谢您的评论。这让我走上了一条“更好”的道路,或者至少让我得到了答案。
推荐阅读
- laravel - Laravel 缓存键前缀带有数据库前缀
- c# - 使用 DbCommand 的数组绑定参数
- javascript - 如何使用给定的属性值计算数组中的对象(Angular-FirebaseRealtime)
- xml - 如何在 Spark SQL 中解析 XML?
- javascript - SAPUI5 列表/组合框数据绑定替换为表格
- django - 对 Django 和 Angular 应用程序的 CSRF 保护
- chatbot - 我需要一个建议来制作一个聊天机器人
- php - PHP:在 for 循环中出现计算问题
- excel - 使用VBA将特定列从一个隐藏工作表复制到另一个工作表,目标顺序也是特定顺序
- r - 有任何方法可以将空间点插入 R 中的空间像素网格中