Data Validation
There are multiple schema defined for validation of different datasets at different pipeline stages.
validate_dataframe(df, schema, **kwargs)
Validates data against a specified schema.
The data should have been prepared as per the specification set by the lead site. Use the output of this function to iteratively identify and address data quality issues.
The following schema are defined:
Admitted Care Data:
AdmittedCareEpisodeSchema
AdmittedCareFeatureSchema
Emergency Care Data:
EmergencyCareEpisodeSchema
EmergencyCareFeatureSchema
See source code for validation rules.
Returns a good dataframe containing rows that passed validation and a bad dataframe with rows that failed validation. The bad dataframe has additional columns that provide information on failure cause(s). If there is a column error (misspelt, missing or additional), all rows will be returned in bad dataframe.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
DataFrame
|
Dataframe to be validated |
required |
schema |
DataFrameSchema
|
Pandera schema to validate against |
required |
kwargs |
The following keyword arguments are currently supported |
{}
|
|
start_date |
datetime
|
Study start date (inclusive) |
required |
end_date |
datetime
|
Study end date (excluded) |
required |
ignore_cols |
list
|
Columns to ignore during validation checks. |
required |
update_cols |
dict[str
|
dict]): Dictionary of column:properties to update schema. |
required |
Returns:
Type | Description |
---|---|
Tuple[DataFrame, DataFrame]
|
Good and Bad dataframes. See example below. |
Validation example
from avoidable_admissions.data.validate import (
validate_dataframe,
AdmittedCareEpisodeSchema
)
df = pd.read_csv('path/to/data.csv')
good, bad = validate_dataframe(df, AdmittedCareEpisodeSchema)
If df
had rows that fail validation, the function will print an output similar to below.
Schema AdmittedCareEpisodeSchema: A total of 1 schema errors were found.
Error Counts
------------
- schema_component_check: 1
Schema Error Summary
--------------------
failure_cases n_failure_cases
schema_context column check
Column admiage greater_than_or_equal_to(18) [17.0] 1
This message indicates that there was a validation error in the admiage
column which expects values >=18.
Fix data quality iteratively to ensure there are no errors.
If you find a bug in the validation code, and correct data fails validation, please raise a GitHub issue.
Customising validation
Customise study dates
As a default, the study dates specified in the initial protocol will be used
(admidate>=datetime(2021,11,1) and admidate<datetime(2022,11,1)
).
However, these can be altered by providing these as keyword arguments.
The following rule is applied to admidate
in the Acute Admissions dataset
and to edarrivaldatetime
in the emergency care dataset.
admidate>=start_date
and admidate<end_date
The <end_date
allows 31-10-2022 23:59:00
to pass validation when
end_date
is set to datetime(2022,11,1)
.
Ignore selected columns
Passing a list of column names toignore_cols
as a keyword argument will
apply the following properties, effectively turning off validation.
{
'dtype': None,
'checks': [],
'nullable': False,
'unique': False,
'coerce': False,
'required': True
}
Update validation rules
Passing a dictionary of {column_name: property_dict} allows fine-grained control.
For example, to update remove checks on edchiefcomplaint
but preserve
other validation rules, pass the following to update_cols
.
Custom validation example
The example below applies the following custom rules:
- Change study start and end dates
- Ignore validation on
eddiag_NN
columns. This requires both _01 and _[0-9]{2}$ regex suffixes to be set. Note the $ at the end of regex. - Don't perform checks on
edchiefcomplaint
but retain other rules e.g dtype - Dont' check data type for
accommodationstatus
but retain other rules
good, bad = validate_dataframe(
df,
schema,
start_date=datetime(2021, 10, 1),
end_date=datetime(2022, 11, 1),
ignore_cols=["eddiag_01", "eddiag_[0-9]{2}$"],
update_cols={
"edchiefcomplaint": {"checks": []},
"accommodationstatus": {"dtype": None},
}
)
Source code in avoidable_admissions/data/validate.py
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 |
|
validate_admitted_care_data(df, **kwargs)
Convenience wrapper for validate_dataframe(df, AdmittedCareEpisodeSchema)
See avoidable_admissions.data.validate.validate_dataframe for usage.
Source code in avoidable_admissions/data/validate.py
773 774 775 776 777 778 779 780 781 |
|
validate_admitted_care_features(df, **kwargs)
Convenience wrapper for validate_dataframe(df, AdmittedCareFeatureSchema)
See avoidable_admissions.data.validate.validate_dataframe for usage.
Source code in avoidable_admissions/data/validate.py
794 795 796 797 798 799 800 801 |
|
validate_emergency_care_data(df, **kwargs)
Convenience wrapper for validate_dataframe(df, EmergencyCareEpisodeSchema)
See avoidable_admissions.data.validate.validate_dataframe for usage.
Source code in avoidable_admissions/data/validate.py
784 785 786 787 788 789 790 791 |
|
validate_emergency_care_features(df, **kwargs)
Convenience wrapper for validate_dataframe(df, EmergencyCareFeatureSchema)
See avoidable_admissions.data.validate.validate_dataframe for usage.
Source code in avoidable_admissions/data/validate.py
804 805 806 807 808 809 810 811 |
|
get_schema_properties(schema)
Get detailed information about a validation schema including checks, dtypes, nullability and more.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema |
Pandera DataFrameSchema
|
One of |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: Dataframe containing schema properties. |
Source code in avoidable_admissions/data/validate.py
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 |
|
Fixing Errors
It is likely that data validation will fail on a subset of the data the first few times. Fixing errors will be an iterative process and the following are some examples.
Please see https://mattstammers.github.io/hdruk_avoidable_admissions_collaboration_docs/ for more examples.
Errors in validation after feature generation may be caused by extraneous codes that are not specified in the data specification.
Examples
# Convert to date
df['admidate'] = pd.to_datetime(df['admidate'], yearfirst=True)
df['admidate'] = df['admidate'].dt.date
# Fill missing SNOMED codes with 0.
# Else valiation will fail as nan is treated as float.
df['accommodationstatus'] = df['accommodationstatus'].fillna(0)
Missing Values
To be finalised after further discussion and testing.
There is an entire chapter in Pandas documentation on missing values which is an important read for any data scientist.
For the purposes of this project, several pragmatic choices have been made regarding how missing values are treated.
- Where a definition exists for how missing values should be coded, for instance in the NHS data model, use this.
- For SNOMED codes, which are always integers, use 0 (zero) to replace all missing values. This avoids validation errors caused by
NaN
values that are treated asfloat
dtype by Pandas. - For strings, use
"-"
(without the quotes) for missing values. - During feature engineering, custom error values are assigned to codes that are missing from either the refsets or mapping.