Threshold-based cleaning
Sanitize tabular measurements by replacing values that violate a threshold.
Pandas · Module
DataFrame.mask replaces values where a condition is True and keeps values where it is False. Replacement values come from other, or from dtype-appropriate nulls when other is omitted.
DataFrame.mask evaluates a boolean condition element by element. Values where the condition is False remain unchanged; values where it is True come from other, or become the dtype-appropriate missing value when other is omitted. The operation returns a DataFrame unless inplace=True.
DataFrame.mask(cond, other=<no_default>, *, inplace=False, axis=None, level=None)| Name | Type | Description |
|---|---|---|
cond | bool Series/DataFrame, array-like, or callable | Boolean Series/DataFrame, array-like, or callable selecting entries to replace; False entries are retained. |
other | scalar, Series/DataFrame, or callable | Scalar, Series/DataFrame, or callable supplying replacement values; omitted values become dtype-appropriate nulls. |
inplace | bool, default False | Whether to perform the operation in place. |
axis | int, default None | Alignment axis when needed. |
level | int, default None | Alignment level when needed. |
A DataFrame when called on a DataFrame; None when inplace=True.
import pandas as pd
scores = pd.DataFrame({"math": [72, 91], "science": [88, 64]})
result = scores.mask(scores < 70, other=0)
print(result)Replaces every score below 70 with zero while leaving all other values unchanged.
Sanitize tabular measurements by replacing values that violate a threshold.
Redact selected cells while preserving the rest of a DataFrame.
Apply a scalar, aligned object, or computed replacement to matching entries.
mask replaces elements where cond is True and preserves elements where cond is False. With a DataFrame input, it returns a DataFrame unless inplace=True.
Follow-up: How does mask differ from where? where replaces values where the condition is False, while mask replaces values where it is True.
cond can be a boolean Series, DataFrame, array-like object, or callable. A callable is evaluated against the DataFrame and must produce a boolean Series, DataFrame, or array.
Follow-up: What restriction applies to that callable? It must not modify the input DataFrame, even though pandas does not validate this.
other may be a scalar, Series, DataFrame, or callable. If omitted, positions selected by cond are filled with the appropriate null value, such as np.nan for NumPy dtypes or pd.NA for extension dtypes.
Follow-up: What happens when replacement labels do not align with the condition? Misaligned condition positions are treated as True and therefore are replaced.
DataFrame.whereSeries.maskSeries.where