|
1 | 1 | import pandas as pd |
2 | 2 |
|
3 | 3 |
|
4 | | -def check_nat_val(df: pd.DataFrame, breakdown_col: str = "Breakdown", |
5 | | - measure_col: str = "Measure", value_col: str = |
6 | | - "Value_Unsuppressed", nat_val: str = "National") -> bool: |
| 4 | +def check_nat_val( |
| 5 | + df: pd.DataFrame, |
| 6 | + breakdown_col: str = "Breakdown", |
| 7 | + measure_col: str = "Measure", |
| 8 | + value_col: str = "Value_Unsuppressed", |
| 9 | + nat_val: str = "National", |
| 10 | +) -> bool: |
7 | 11 | """ |
8 | 12 | Check national value less than or equal to sum of breakdowns. |
9 | 13 |
|
@@ -66,24 +70,32 @@ def check_nat_val(df: pd.DataFrame, breakdown_col: str = "Breakdown", |
66 | 70 | False |
67 | 71 | """ |
68 | 72 |
|
69 | | - if not isinstance(breakdown_col, str) or not isinstance(measure_col, str)\ |
70 | | - or not isinstance(value_col, str): |
| 73 | + if ( |
| 74 | + not isinstance(breakdown_col, str) |
| 75 | + or not isinstance(measure_col, str) |
| 76 | + or not isinstance(value_col, str) |
| 77 | + ): |
71 | 78 | raise ValueError("Please input strings for column indexes.") |
72 | 79 | if not isinstance(nat_val, str): |
73 | 80 | raise ValueError("Please input strings for value indexes.") |
74 | | - if breakdown_col not in df.columns or measure_col not in df.columns or\ |
75 | | - value_col not in df.columns: |
| 81 | + if ( |
| 82 | + breakdown_col not in df.columns |
| 83 | + or measure_col not in df.columns |
| 84 | + or value_col not in df.columns |
| 85 | + ): |
76 | 86 | raise KeyError("Check column names correspond to the DataFrame.") |
77 | | -# aggregate values by measure and breakdown |
78 | | - grouped = df.groupby([measure_col, breakdown_col]).agg({value_col: sum})\ |
79 | | - .reset_index() |
| 87 | + # aggregate values by measure and breakdown |
| 88 | + grouped = ( |
| 89 | + df.groupby([measure_col, breakdown_col]).agg({value_col: sum}).reset_index() |
| 90 | + ) |
80 | 91 | national = grouped.loc[grouped[breakdown_col] == nat_val].reset_index() |
81 | 92 | non_national = grouped.loc[grouped[breakdown_col] != nat_val].reset_index() |
82 | | -# check values are less than or equal to national value for each measure |
83 | | - join = pd.merge(non_national, national, left_on=measure_col, |
84 | | - right_on=measure_col, how='left') |
85 | | - left = value_col + '_x' |
86 | | - right = value_col + '_y' |
87 | | - join['Check'] = join[right] <= join[left] |
88 | | - result = all(join['Check']) |
| 93 | + # check values are less than or equal to national value for each measure |
| 94 | + join = pd.merge( |
| 95 | + non_national, national, left_on=measure_col, right_on=measure_col, how="left" |
| 96 | + ) |
| 97 | + left = value_col + "_x" |
| 98 | + right = value_col + "_y" |
| 99 | + join["Check"] = join[right] <= join[left] |
| 100 | + result = all(join["Check"]) |
89 | 101 | return result |
0 commit comments