Skip to content

pandas/value-counts-share

Rule value-counts-share
Pack pandas
Severity warning
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

Dividing value_counts() by the length computes shares by hand. Call value_counts(normalize=True) instead.

shares = df["region"].value_counts() / len(df["region"])
shares = df["region"].value_counts(normalize=True)

The rule reports df["k"].value_counts() / len(df["k"]). The fix is unsafe, because it names the result proportion instead of count, and it leaves missing values out of the total.

xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.

The unsafe fix writes df["k"].value_counts(normalize=True).

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

value_counts(normalize=True) returns the shares directly. Write $S.value_counts(normalize=True).

Browse the other rules of the pandas pack.