Python

groupby + transform: row-aligned features

transform returns a Series the same size as the original DataFrame: perfect for normalizing each row against its group.

Prerequisites

Python 3.9+, pandas

Python
import pandas as pd

g = df.groupby("categorie")["montant"]

# Score z calculé PAR GROUPE, aligné sur les lignes d'origine
df["zscore_grp"] = (df["montant"] - g.transform("mean")) / g.transform("std")

# Part de chaque ligne dans le total de son groupe
df["part_grp"] = df["montant"] / g.transform("sum")

# Lignes anormales au sein de leur propre segment
outliers = df[df["zscore_grp"].abs() > 3]

Result

>>> outliers[["categorie", "montant", "zscore_grp", "part_grp"]]
         categorie  montant  zscore_grp  part_grp
842   informatique  48900.0        3.42     0.118
1217      mobilier  31200.0        3.87     0.094
3406  informatique  52750.0        3.71     0.127
PandasgroupbytransformOutliers

Related snippets

Back to the Data Lab