python - 使用 pandas 模式的 Python 库列验证
问题描述
我正在尝试使用 PandasSchema 验证我的 DataFrame 库。我一直在验证某些列,例如:
1.ip_address- 应包含以下格式 1.1.1.1 的 ip 地址,或者如果任何其他值应引发错误,则应为 null。2.initial_date- 格式 yyyy-mm-dd h:m:s 或 mm-dd-yyyy h:m:s 等 3.customertype 应为 ['type1','type2','type3'] 其他任何内容一个错误。4.customer 满意= yes/no 或空白 5.customerid 不应超过 5 个字符,例如 cus01、cus02 6.time 应采用 %:%: 格式或 h:m:s 格式,其他任何内容都会引发异常。
from pandas_schema import Column, Schema
def check_string(sr):
try:
str(sr)
except InvalidOperation:
return False
return True
def check_datetime(self,dec):
try:
datetime.datetime.strptime(dec, self.date_format)
return True
except:
return False
def check_int(num):
try:
int(num)
except ValueError:
return False
return True
string_validation=[CustomElementValidation(lambda x: check_string(x).str.len()>5 ,'Field Correct')]
int_validation = [CustomElementValidation(lambda i: check_int(i), 'is not integer')]
contain_validation = [CustomElementValidation(lambda y: check_string(y) not in['type1','type2','type3'], 'Filed is correct')]
date_time_validation=[CustomElementValidation(lambda dt: check_datetime(dt).strptime('%m/%d/%Y %H:%M %p'),'is not a date
time')]
null_validation = [CustomElementValidation(lambda d: d is not np.nan, 'this field cannot be null')]
schema = Schema([
Column('CompanyID', string_validation + null_validation),
Column('initialdate', date_time_validation),
Column('customertype', contain_validation),
Column('ip', string_validation),
Column('customersatisfied', string_validation)])
errors = schema.validate(combined_df)
errors_index_rows = [e.row for e in errors]
pd.DataFrame({'col':errors}).to_csv('errors.csv')
解决方案
我刚刚查看了 PandasShema 的文档,并且大多数(如果不是全部)您正在寻找它的开箱即用功能。看一眼:
作为解决您的问题的快速尝试,类似的方法应该有效:
from pandas_schema.validation import (
InListValidation
,IsDtypeValidation
,DateFormatValidation
,MatchesPatternValidation
)
schema = Schema([
# Match a string of length between 1 and 5
Column('CompanyID', [MatchesPatternValidation(r".{1,5}")]),
# Match a date-like string of ISO 8601 format (https://www.iso.org/iso-8601-date-and-time-format.html)
Column('initialdate', [DateFormatValidation("%Y-%m-%d %H:%M:%S")], allow_empty=True),
# Match only strings in the following list
Column('customertype', [InListValidation(["type1", "type2", "type3"])]),
# Match an IP address RegEx (https://www.oreilly.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html)
Column('ip', [MatchesPatternValidation(r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}")]),
# Match only strings in the following list
Column('customersatisfied', [InListValidation(["yes", "no"])], allow_empty=True)
])
推荐阅读
- plantuml - plantuml : 分组序列使演员出现
- reactjs - 在 React 中,为什么在某些情况下会渲染两次?
- python - 模块“matplotlib”在 Django 中没有属性“switch_backend”
- asp.net - github 中 EF plus 审计功能的工作示例
- scrapy - Scrapy:(400 Bad Request)HTTP状态码未处理或不允许
- kubernetes-service - Kubernetes ClusterIP 服务只能从端点存在的节点访问
- c# - 在两个垂直注释之间创建一条箭头线
- julia - 如何在 Julia 中适当地调用参数构造函数?
- php - 为什么 HTML 文件的 PHP 版本不显示所有元素?
- python - 用于对python中的所有分类变量进行详尽的卡方检验和方差分析的函数