【发布时间】:2021-01-15 17:08:39
【问题描述】:
我正在尝试使用 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 应该是 in['type1','type2','type3'] 其他任何东西都会引发错误。 4.客户满意=是/否或空白 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')
【问题讨论】:
标签: python pandas dataframe validation customvalidator