Pucktrick
Pucktrick is a Python library that provides utility functions for introducing errors in your dataframe. The library's name is based on Puck. Puck is the name of the elf in the "A Midsummer Night's Dream" of William Shakespeare, who is very famous for causing trouble and playing tricks on mortals and other fairies alike.
Features
Pucktrick is organized in modules, one for each error type. Each module includes a main function (or a class injector) that receives as parameters the dataset to modify, the strategy dictionary, and the original dataset if mode="extended" or mode="composed". Functions return two parameters: an error descriptor and the generated dataset.
For standard error modules, the error descriptor is an integer code (0 = success, 1 = no modifications applied). For the drift module, it is a dictionary with richer information (see Drift Simulation).
The Strategy Configuration
The core of Pucktrick is the strategy configuration, which is passed as a JSON object or a Python dictionary. It allows you to precisely define the error model.
Base Parameters
{
"affected_features": ["column1", "column2"],
"selection_criteria": "all",
"percentage": 0.2,
"mode": "new",
"perturbate_data": {
"sampling": "random"
}
}
affected_features: A list of strings specifying the columns to be corrupted.selection_criteria: A predicate (e.g.,"age > 30") to target specific rows, or"all"to target the entire dataset.percentage: A float (0.0 to 1.0) indicating the proportion of targeted rows to corrupt.mode:"new": Applies errors independently to the clean baseline datasetD0. Each call is stateless."extended": Incrementally adds errors to a previously corrupted dataset. Readsoriginal_df(the cleanD0) to identify rows already modified and adds corruption only to unmodified rows, up to the cumulativepercentagetarget. No row is corrupted twice."composed": Applies errors exclusively to rows that have already been modified by a previous operator, usingoriginal_df(the cleanD0) to identify them via a row-level, NaN-aware comparison across all columns. Thepercentageparameter controls what fraction of the already-modified set to corrupt. This enables cross-type corruption pipelines where heterogeneous errors are layered on the same row subset.
perturbate_data: A dictionary containing the noise injection logic.sampling: How rows are chosen ("random","uniform","normal","exponential").
Accumulation Modes: Summary
| Mode | Eligible rows | percentage applies to |
Requires original_df |
|---|---|---|---|
new |
All rows | Full eligible set | No |
extended |
Rows not yet modified | Full eligible set (cumulative) | Yes |
composed |
Rows already modified in any column | Already-modified set | Yes |
Example: Composed Pipeline
from pucktrick.missing import missing
from pucktrick.outliers import outlier
# Step 1 — inject missing values on c1 (20% of rows), mode="new"
strategy_s1 = {
"affected_features": ["c1"],
"selection_criteria": "c1 == c1",
"percentage": 0.20,
"mode": "new",
"perturbate_data": {"sampling": "random"}
}
err1, D1 = missing(df, strategy_s1)
# Step 2 — inject outliers on c2, mode="composed"
# Acts exclusively on the rows already modified by Step 1
strategy_s2 = {
"affected_features": ["c2"],
"selection_criteria": "c2 == c2",
"percentage": 1.0,
"mode": "composed",
"perturbate_data": {"sampling": "random"}
}
err2, D2 = outlier(D1, strategy_s2, original_df=df)
# D2: rows with NaN in c1 coincide exactly with rows with outliers in c2
Modules & Specific Configurations
Error Injection Modules
1. Missing (missing.py)
Replaces values with NaN.
Specifics: No special parameters required in perturbate_data.
2. Outliers (outliers.py)
Injects outliers using a 3-sigma rule for continuous numeric data, domain expansion for categorical integers, or specific string tokens for text.
Specifics: No special parameters required in perturbate_data.
3. Duplicated (duplicated.py)
Duplicates existing rows and optionally applies text transformations.
Specifics: Set "function" in the main strategy to apply text transformations like "shuffle_words", "abbreviate_text", "replace_punctuation", "remove_replace", or "upper_lower".
4. Noisy (noisy.py)
Adds random noise or a systematic shift to data (numeric, string, or datetime).
Specifics: In perturbate_data, set "distribution": "shift" to apply systematic shifting. You must provide a "param" dictionary:
"shift_value": Numeric value to add (or days for dates)."shift_unit":"absolute"or"std"(standard deviations)."shift_sign":"positive","negative", or"random".
(Use "distribution": "random" for standard uniform noise).
5. Labels (labels.py)
Flips labels for binary or multi-class classification.
Specifics: For multi-class labels in perturbate_data, set "noise_model" to:
"NCAR"(Noise Completely At Random): Uniform random flip."NAR"(Noise At Random): Class-dependent flip. Provide"flip_distribution"inparam."NNAR"(Nearest Neighbor At Random): Flips labels of instances close to decision boundaries. Provide"features_for_similarity"inparam.
Drift Simulation
Pucktrick supports the simulation of dataset drift modelled as temporal corruption policies applied to dataset segments. Drift is exposed through a single unified function drift() that follows the same calling convention as all other modules:
from pucktrick.drift import drift
strategy = {
"affected_features": ["f1", "f2"],
"selection_criteria": "all",
"percentage": 0.35, # fraction of rows affected per chunk
"mode": "new",
"perturbate_data": {
"sampling": "random",
"target_col": "target", # omit for auto-detection
"chunks": {
"0": None, # baseline segment, no drift
"1": None,
"2": { ... }, # drift configuration for segment 2
"3": { ... },
}
}
}
error, df_modified = drift(df, strategy)
Unlike other modules, the error return value is a dictionary:
{
"errore": "yes", # "yes" if any modification occurred, "no" otherwise
"change_points": [100, 200, 300], # row indices delimiting chunk boundaries
"chunks": {
"0": {"start": 0, "end": 100, "drift_applied": False},
"1": {"start": 100, "end": 200, "drift_applied": False},
"2": {"start": 200, "end": 300, "drift_applied": True},
"3": {"start": 300, "end": 400, "drift_applied": True},
}
}
Note:
samplinganddistributionparameters insideperturbate_dataare not used by the drift module — row selection within each chunk is always random and controlled exclusively bypercentage.
Drift Types Summary
| Drift type | Distribution affected | Module | drift_type value |
|---|---|---|---|
| Data drift (covariate noise) | $P(X)$ changes | covariate_noise_drift |
"covariate_noise" |
| Data drift (offset) | $P(X)$ changes | covariate_offset_drift |
"covariate_offset" |
| Concept drift (target offset) | $P(Y|X)$ changes | offset_drift |
"concept" |
| Concept drift (feature rotation) | $P(Y|X)$ changes | concept_drift |
"concept_rotation" |
| Label drift (prior shift) | $P(Y)$ changes | prior_multinomial_drift |
"prior_multinomial" |
| Target scaling | $P(Y)$ changes | target_scaling_drift |
"target_scaling" |
| Generic (all types) | configurable | drift_generic |
any |
6. Covariate Noise Drift (covariate_noise_drift.py)
Adds progressive Gaussian noise to selected features, simulating data drift where $P(X)$ shifts over time.
"2": {
"drift_type": "covariate_noise",
"features": ["temp", "humidity"],
"noise_mode": "relative",
"noise_std": 0.08,
"shape": "segment"
}
"noise_mode":"relative"(noise proportional to feature std) or"absolute""noise_std": magnitude of Gaussian noise"shape":"segment"(this chunk only) or"step"(persists in subsequent chunks)
7. Covariate Offset Drift (covariate_offset_drift.py)
Applies a systematic directional offset to selected features, simulating sensor calibration drift.
"2": {
"drift_type": "covariate_offset",
"features": ["temp", "humidity"],
"offset_mode": "relative",
"offset_scale": 0.20,
"direction": "up",
"shape": "step"
}
"offset_mode":"relative"or"absolute""offset_scale": magnitude of the offset"direction":"up","down", or"random""shape":"segment"or"step"
8. Concept Drift — Target Offset (offset_drift.py)
Shifts the target variable using a percentage offset, simulating concept drift where $P(Y \mid X)$ changes.
"2": {
"drift_type": "concept",
"features": ["<TARGET>"],
"offset_perc": 0.50,
"offset_mode": "add",
"base": "mean",
"shape": "step",
"direction": "up"
}
"offset_perc": fractional offset applied to the base value"offset_mode":"add"or"mul"(multiplicative)"base":"mean","median","std", or"quantile""shape":"step","ramp","spike", or"sin"
9. Concept Drift — Feature Rotation (concept_drift.py)
Permutes or cycles feature values across instances, breaking the feature-label relationship without altering marginal distributions.
"2": {
"drift_type": "concept_rotation",
"severity": 0.65,
"rotation_mode": "cycle",
"shape": "step"
}
"severity": fraction of features involved (0.0–1.0)"rotation_mode":"cycle"or"permute"
10. Label Drift — Prior Multinomial (prior_multinomial_drift.py)
Resamples the class distribution according to a user-specified probability vector, simulating prior probability shift $P(Y)$.
"2": {
"drift_type": "prior_multinomial",
"features": ["<TARGET>"],
"bins": 3,
"class_probs_list": [0.05, 0.15, 0.80],
"temperature": 0.6
}
"bins": number of bins for numeric columns"class_probs_list": probability vector for each bin/class"temperature": sharpens (< 1.0) or flattens (> 1.0) the distribution
11. Target Scaling (target_scaling_drift.py)
Applies a multiplicative scaling factor to the numeric target variable.
"2": {
"drift_type": "target_scaling",
"scale_perc": 0.10,
"shape": "segment"
}
"scale_perc": fractional increase (e.g.,0.10multiplies target by 1.10)"scale_factor": direct multiplicative factor (alternative toscale_perc)
12. Generic Drift (drift_generic.py)
A unified module supporting all drift types above plus additional specialized types (conditional, offset_time, seasonal_shift, prior_bool, concept_ord_shift, and others).
Version
version 1.0.1
- Unified drift interface:
drift()now follows the same calling convention as all other error modules (error, df_modified = drift(df, strategy)). - The
errorreturn value for drift is now a dictionary containingerrore(yes/no),change_points, and per-chunk metadata (start,end,drift_applied). - Removed debug print statements from
drift.pyanddrift_generic.py.
version 1.0.0
- Added drift simulation modules:
covariate_noise_drift,covariate_offset_drift,offset_drift,concept_drift,prior_multinomial_drift,target_scaling_drift,drift_generic. All modules support bothstrategy_path(JSON file) andstrategy(Python dict) as input. - Added unified
drift.pywrapper exposing adrift()function compatible with the PuckTrick strategy interface. - All drift modules integrated and tested with synthetic datasets.
version 0.6.1.1
- Added
composedmode to all modules. - Added
_is_row_modifiedmethod toBaseErrorInjectorfor row-level modification tracking. - Fixed
_get_modifiable_maskinMissingErrorInjectorandLabelErrorInjector. - Fixed type normalization in NAR label flip for integer target columns.
version 0.6.0.1
- Codebase fully refactored using Object-Oriented Programming with the Template Method Pattern.
- Added systematic shift (
"distribution": "shift") to thenoisymodule. - Standardized the
strategyinterface and improvedextendedmode logic across all modules.
version 0.5.1
- add multiclass definition
version 0.5
- add strategy JSON configuration.
version 0.4
- errortype added: missing values
version 0.3
- error type added: duplicated
version 0.2
- error type inserted: outliers
version 0.1
- error type inserted: noisy error and inconsistency labels
Installation
pip install pucktrick
Contributing
- Fork the repository
- Create a new branch (
git checkout -b feature/your-feature) - Commit your changes (
git commit -am 'Add new feature') - Push to the branch (
git push origin feature/your-feature) - Create a new Pull Request
License
This project is licensed under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) — see the LICENSE file for details.
Acknowledgements
Thanks to the contributors and open-source community for their support.
Metadata
Release files for pucktrick 1.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pucktrick-1.1.0.tar.gz | 64.2 kB | Without provenance | Details for pucktrick-1.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pucktrick-1.1.0-py3-none-any.whl | Python 3 | none | any | Details for pucktrick-1.1.0-py3-none-any.whl |
Total release size: 126.6 kB
Release files / pucktrick-1.1.0.tar.gz
| Download URL | pucktrick-1.1.0.tar.gz |
|---|---|
| Size | 64.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
fa89b0d85f1acb2b74d71599296976812f9da792d7027b63f3bddfa4648c6b93
|
|
BLAKE2b-256 checksum How to use checksums |
f44c16eb69f51e38b1cb80718b6a08c748079063ab8878dc182dfde07a9b9b28
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.11.5
|
Release files / pucktrick-1.1.0-py3-none-any.whl
| Download URL | pucktrick-1.1.0-py3-none-any.whl |
|---|---|
| Size | 62.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9771f72d15ace897ccc94c43a473183a20fe16aa6c52dadf6073435c5ace85bd
|
|
BLAKE2b-256 checksum How to use checksums |
0118d10e3fbc335fbf677f928309408523e694b8e1e059783bcbbc2d62881711
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.11.5
|
Security for pucktrick 1.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.