Я пытаюсь проверить свои столбцы DataFrame с помощью схемы Pandas. Я застрял в проверке некоторых столбцов, таких как столбцы, например:

1. ip_address - должен содержать IP-адрес в следующем формате 1.1.1.1 или должен быть нулевым, если любое другое значение должно вызывать ошибку. 2. исходная_дата- формат гггг-мм-дд ч: м: с или мм-дд-гггг ч: м: с и т. Д. 3. тип клиента должен быть в ['type1', 'type2', 'type3'] что-нибудь еще поднять ошибка. 4. клиент удовлетворен = да / нет или пусто 5. идентификатор клиента не должен быть длиннее 5 символов eg- cus01, cus02 6. время должно быть в формате%:%: или 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')
0
Ankit Kumar Sharma 30 Сен 2020 в 06:53

1 ответ

Лучший ответ

Я только что просмотрел документацию для 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)
])
0
Fred 30 Сен 2020 в 10:51