Data¶
data ¶
Assembly: mathy Filename: data.py Author: Terry D. Eppler Created: 05-31-2022
Last Modified By: Terry D. Eppler Last Modified On: 05-01-2025
data.py
Copyright © 2023 Terry Eppler
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
You can contact me at: terryeppler@gmail.com or eppler.terry@epa.gov
DataSource ¶
Prepare tabular modeling data.
Purpose
Wraps a pandas DataFrame with derived metadata, descriptive statistics, train/test splits, categorical and numeric partitions, encoding hooks, scaling hooks, pivot creation, export, and profiling utilities. The wrapper preserves the selected target column and maintains synchronized feature, target, numeric, categorical, and split attributes after supported transformations.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
DataFrame
|
Working dataframe used by transformation and analysis methods. |
size |
float
|
Test-set proportion used for train/test splitting. |
seed |
int
|
Random seed used by the splitter. |
scaler |
Optional[Scaler]
|
Most recent scaler wrapper used by scaling methods. |
label_encoder |
Optional[OrdinalEncoder]
|
Most recent label or ordinal encoder wrapper. |
target_encoder |
Optional[TargetEncoder]
|
Target encoder reserved for target-aware encoding. |
target |
Optional[str]
|
Name of the selected target column. |
targets |
Optional[ndarray]
|
Current target values from the working dataframe. |
n_samples |
Optional[int]
|
Number of rows in the working dataframe at initialization. |
n_features |
Optional[int]
|
Number of non-target columns at initialization. |
percentiles |
Optional[List[float]]
|
Percentile boundaries used to summarize numeric distributions. |
scaling_factor |
Optional[int]
|
Multiplicative factor applied during data scaling. |
feature_names |
Optional[List[str]]
|
Current non-target feature column names. |
target_names |
Optional[ndarray]
|
Sorted unique target values. |
categorical_columns |
Optional[List[str]]
|
Current categorical column names. |
numeric_columns |
Optional[List[str]]
|
Current numeric column names. |
numeric_data |
Optional[DataFrame]
|
Current numeric-column dataframe slice. |
categorical_data |
Optional[DataFrame]
|
Current categorical-column dataframe slice. |
datatuple |
Optional[List[Tuple[str, Encoder, List[str]]]]
|
ColumnTransformer definitions. |
numeric_metrics |
Optional[DataFrame]
|
Descriptive statistics for numeric columns. |
pivot_table |
Optional[DataFrame]
|
Most recent pivot table generated by
|
mean_standard_error |
Optional[DataFrame]
|
Standard error calculated from the feature means. |
average |
Optional[Series]
|
Averaging strategy or calculated arithmetic-mean values. |
kurtosis |
Optional[Series]
|
Calculated kurtosis values for numeric features. |
skew |
Optional[Series]
|
Calculated skewness values for numeric features. |
variance |
Optional[Series]
|
Calculated variance values for numeric features. |
covariance |
Optional[DataFrame]
|
Calculated covariance matrix for numeric features. |
standard_deviation |
Optional[Series]
|
Calculated standard-deviation values for numeric features. |
column_transformer |
Optional[ColumnTransformer]
|
Most recent fitted column transformer. |
X_training |
Optional[DataFrame]
|
Feature training split. |
X_testing |
Optional[DataFrame]
|
Feature testing split. |
y_training |
Optional[Series]
|
Target training split. |
y_testing |
Optional[Series]
|
Target testing split. |
Source code in data.py
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 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 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 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 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 | |
transform_columns ¶
Transform selected columns.
Purpose
Adds a named encoder definition to the internal ColumnTransformer, fits the transformer against current feature columns, rebuilds the working dataframe with transformed and passthrough columns, preserves the target values, refreshes metadata, and recreates the train/test split from the transformed dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Transformer name used inside the ColumnTransformer definition. |
required |
encoder
|
Encoder
|
Encoder or transformer wrapper applied to the selected columns. |
required |
columns
|
List[str]
|
Column names transformed by the supplied encoder. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Updated working dataframe after column transformation. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when validation, transformation, dataframe reconstruction, or split refresh fails. |
Source code in data.py
standardize ¶
Standardize numeric data.
Purpose
Applies the sklearn StandardScaler wrapper to the current numeric dataframe slice and returns the standardized numeric matrix. The fitted scaler is stored on the instance for later inspection or inverse transformation when supported by the scaler wrapper.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Standardized numeric data produced by the scaler wrapper. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when scaler construction or numeric transformation fails. |
Source code in data.py
maxminize ¶
Scale numeric data to a bounded range.
Purpose
Applies the MinMaxScaler wrapper to the current numeric dataframe slice and returns the scaled numeric matrix. The fitted scaler is stored on the instance so the scaling operation remains discoverable after execution.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Min-max scaled numeric data produced by the scaler wrapper. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when scaler construction or numeric transformation fails. |
Source code in data.py
normalize ¶
Normalize numeric data.
Purpose
Applies the NormalScaler to the current numeric dataframe slice and returns the normalized numeric matrix. The fitted scaler is stored on the instance for consistent access after the normalization operation completes.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Normalized numeric data produced by the scaler wrapper. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when scaler construction or numeric transformation fails. |
Source code in data.py
encode_labels ¶
Encode a label column.
Purpose
Fits a LabelEncoder wrapper to the specified dataframe column, writes encoded labels back into the working dataframe, and refreshes target, numeric, or categorical cached slices when the encoded column participates in those instance attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
str
|
Name of the dataframe column to label-encode. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Encoded label array produced by the label encoder. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when validation, encoder fitting, transformation, or cache refresh fails. |
Source code in data.py
encode_features ¶
Encode feature columns.
Purpose
Applies an OrdinalEncoder wrapper to every non-target column, rebuilds the working dataframe with encoded features and the unchanged target column, refreshes metadata and cached slices, and recreates the train/test split from the encoded feature set.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Updated working dataframe with encoded feature columns. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when feature collection, encoding, dataframe reconstruction, or split refresh fails. |
Source code in data.py
encode_targets ¶
Encode target values.
Purpose
Fits a LabelEncoder wrapper to the current target values, writes encoded targets back into the working dataframe, refreshes target arrays and target names, and recreates the train/test split with the encoded target column.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Encoded target array produced by the label encoder. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when target encoding, metadata refresh, or split recreation fails. |
Source code in data.py
create_pivot ¶
Create a pivot table.
Purpose
Builds a spreadsheet-style pivot table from the working dataframe using explicit row-index, column-axis, and value-column selections. The generated pivot is cached on the instance for later access by reporting or inspection code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cols
|
List
|
Columns used to define the pivot-table column axis. |
required |
vals
|
List
|
Value columns aggregated inside the pivot table. |
required |
idx
|
List
|
Columns used to define the pivot-table row index. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Pivot table generated from the working dataframe. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when validation or pivot-table creation fails. |
Source code in data.py
export_excel ¶
Export data to Excel.
Purpose
Writes the current working dataframe to an Excel workbook at the supplied file path. The method delegates file creation to pandas and preserves the dataframe exactly as stored on the instance at export time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Output workbook path passed to pandas |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
This function performs its work through side effects and does not return a value. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when validation or workbook export fails. |
Source code in data.py
create_histogram ¶
Render a numeric histogram.
Purpose
Aggregates numeric dataframe columns, plots their distribution with seaborn, and renders the histogram through matplotlib for exploratory review of numeric feature totals.
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
This function performs its work through side effects and does not return a value. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when numeric aggregation or plot rendering fails. |
Source code in data.py
create_heatmap ¶
Render a correlation heatmap.
Purpose
Computes the Pearson correlation matrix for the working dataframe and renders a
seaborn heatmap for exploratory analysis of numeric relationships. The numeric
flag controls pandas correlation handling for numeric-only selection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
numeric
|
bool
|
Flag passed to pandas correlation logic for numeric-only behavior. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
This function performs its work through side effects and does not return a value. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when correlation calculation or heatmap rendering fails. |
Source code in data.py
safe_numeric_series ¶
Return a clean numeric series.
Purpose
Converts the selected dataframe column to numeric values, coerces invalid entries to missing values, drops missing observations, and returns a one-dimensional float array suitable for descriptive statistics and distribution profiling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Source dataframe containing the requested column. |
required |
col
|
str
|
Column name converted to numeric values. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: One-dimensional float array with invalid and missing values removed. |
Source code in data.py
create_profile ¶
Create a numeric feature profile.
Purpose
Computes an extended descriptive statistics profile for selected numeric columns, including missing-rate, count, mean, standard deviation, variance, percentile, interquartile range, median absolute deviation, skewness, kurtosis, zero-rate, outlier-rate, and normality fields. The returned profile is sorted to prioritize complete columns with higher IQR-based outlier rates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Source dataframe containing the columns to profile. |
required |
cols
|
List[str]
|
Numeric column names included in the profile. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Dataframe containing one profile row per numeric feature with descriptive and quality metrics. |
Source code in data.py
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 | |
throw_if ¶
Validate a required clustering argument.
Purpose
Enforces the presence of required clustering inputs before estimator execution. The validation accepts populated NumPy arrays and standard Python containers while rejecting null values and empty collections that would otherwise cause downstream sklearn operations to fail or produce undefined clustering results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Argument name used in the validation error message. |
required |
value
|
object
|
Argument value checked for a null or empty state. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
This function performs its work through side effects and does not return a value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Raised when |
Source code in data.py
entropy ¶
Calculate label entropy.
Purpose
Computes Shannon entropy for a one-dimensional label distribution. The calculation converts observed class counts into probabilities and returns a non-negative impurity measure suitable for split evaluation, decision-tree criteria, and information-gain calculations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ndarray
|
Class-label array used to estimate empirical class probabilities. |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: Entropy value for the observed label distribution. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when argument validation or entropy calculation fails. |
Source code in data.py
information_gain ¶
Compute information gain.
Purpose
Calculates the reduction in entropy achieved by splitting a target label vector on a single feature threshold. The result supports decision-tree split selection by comparing parent entropy against the weighted entropy of the left and right partitions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_column
|
ndarray
|
One-dimensional feature array used to form the threshold split. |
required |
y
|
ndarray
|
Target-label array aligned to |
required |
threshold
|
float
|
Split value used to separate left and right partitions. |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: Information-gain value for the requested split, or zero when the split produces an empty partition. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when entropy calculation or threshold partitioning fails. |
Source code in data.py
best_split ¶
Find the best entropy split.
Purpose
Searches each feature column across evenly spaced candidate thresholds and selects the feature-threshold pair with the highest information gain. The returned pair is suitable for constructing a simple decision rule or one-level decision-tree stump.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Feature matrix with rows as samples and columns as candidate split features. |
required |
y
|
ndarray
|
Target-label array aligned to the rows of |
required |
number
|
int
|
Number of candidate thresholds evaluated per feature. |
10
|
Returns:
| Type | Description |
|---|---|
Tuple[int, float] | None
|
Tuple[int, float] | None: Tuple containing the selected feature index and threshold value. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when validation, threshold generation, or information-gain scoring fails. |
Source code in data.py
gini_impurity ¶
Calculate Bernoulli Gini impurity.
Purpose
Computes the Gini impurity for a binary class distribution represented by a success probability. The value measures expected classification impurity and is valid only for probabilities in the inclusive range from zero to one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
float
|
Success probability for the positive class. |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: Gini impurity value for the supplied Bernoulli probability. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when the probability is missing or outside the valid range. |
Source code in data.py
decision_tree_stump ¶
Build a one-level decision stump.
Purpose
Creates a single-feature classification rule by selecting the feature and threshold with maximum information gain. The resulting dictionary stores the selected split and majority labels for the left and right partitions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Feature matrix containing normalized or comparable numeric feature values. |
required |
y
|
ndarray
|
Integer class-label array aligned to the rows of |
required |
num_thresholds
|
int
|
Number of candidate thresholds evaluated per feature. |
10
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict[str, Any]: Dictionary describing the decision stump, or |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when split selection, partitioning, or majority-label calculation fails. |
Source code in data.py
euclidian_distance ¶
Compute distances to centroids.
Purpose
Calculates Euclidean distances from each sample row to each centroid row. The resulting distance matrix supports assignment steps in K-Means-style clustering workflows by identifying the nearest centroid for every sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Feature matrix with rows as samples and columns as features. |
required |
centroids
|
ndarray
|
Centroid matrix with rows as cluster centers and columns as features. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Distance matrix where each row corresponds to a sample and each column corresponds to a centroid. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when validation or distance-matrix construction fails. |
Source code in data.py
k_means ¶
Cluster samples with K-Means.
Purpose
Performs a compact manual K-Means clustering loop using random centroid initialization, Euclidean-distance assignment, centroid recomputation, and early stopping when centroids stabilize. The routine provides a lightweight clustering implementation independent of sklearn estimator classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Feature matrix with rows as samples and columns as numeric features. |
required |
k
|
int
|
Number of clusters to form. |
required |
iters
|
object
|
Maximum number of assignment and centroid-update iterations. |
10
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray] | None
|
Tuple[np.ndarray, np.ndarray] | None: Tuple containing the assigned cluster labels and final centroid matrix. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when validation, centroid initialization, distance calculation, or updates fail. |
Source code in data.py
misclassification_error ¶
Calculate Bernoulli misclassification error.
Purpose
Computes binary misclassification error from a class probability by subtracting the larger class probability from one. The value supports impurity comparisons for simple binary split criteria.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
float
|
Success probability for the positive class. |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: Misclassification error rate for the supplied probability. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when validation or error-rate calculation fails. |
Source code in data.py
sigmoid ¶
Calculate the logistic sigmoid.
Purpose
Maps a real-valued input onto the interval from zero to one using the logistic sigmoid transformation. The input is clipped to a stable exponent range before evaluating the exponential expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
float
|
Real-valued input to transform. |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: Logistic sigmoid value for the supplied input. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised when validation, numeric conversion, clipping, or exponentiation fails. |