Univariate profile#

Profile every column of a data frame in one row: how complete it is, how its values are distributed and, with a binary target, how strongly it separates events from non-events. profile_table() is the first look at the candidates of a model.

See Univariate profile for an example and how to read the profile.

profile_table(frame[, target, columns, ...])

Summarize each column of a data frame in one row.

kivi.univariate.profile_table(frame, target=None, *, columns=None, bins=5, special=None, weights=None)#

Summarize each column of a data frame in one row.

Every column gets its kind, its number of missing values and its most frequent value; numeric columns also get their range, quantiles, mean, standard deviation and shape. With a binary target, each column also gets the event rates of its missing and non-missing rows, the information value and the chi-squared test of a quick binning and, for numeric columns, the Gini coefficient and the KS statistic of its values.

Parameters:
framepandas.DataFrame

One column per variable. Columns with a numeric dtype other than bool are numeric; all others, such as object, string, category or bool, are categorical, as in kivi.spec.fit_spec.

targetarray_like, optional

Binary labels, with 1 indicating the event, one per row of frame. Both classes must be present. A Series must have the same index as frame; other inputs are matched by position. Without target the table describes the columns only.

columnssequence of str, optional

Columns to profile, in the order of the rows. By default every column of frame.

binsint, default 5

Number of quantile bins of the quick binning of numeric columns, from kivi.binning.bin_edges, for the iv column.

specialdict, optional

Special codes of numeric columns, such as {"pdays": [-1]}, as in kivi.spec.fit_spec. They count as values, not as missing, but are left out of the numeric summary and of the Gini coefficient, and each code forms its own group in the quick binning.

weightsarray_like, optional

Non-negative frequency weight of each row, matched like target, such as the inverse of its sampling rate. Counts become sums of weights and every statistic is weighted, so integer weights give the same result as repeating rows with unit weights. Rows with zero weight count for nothing, so their values are not checked. The chi-squared test treats them as frequency weights: a row of weight \(w\) counts as \(w\) observations.

Returns:
pandas.DataFrame

One row per column, indexed by the column names in an index named variable. The columns are described in the Notes.

Raises:
ValueError

If frame is not a DataFrame or has no rows or no columns, columns repeats a column or names one that frame lacks, a column name is not a string, or bins is not a positive integer. If target does not give each row a label 0 or 1, lacks one of the two classes or is a column being profiled, or if weights is invalid or leaves a class without weight. Also if special is not a dict by column, names a column that is not profiled or is categorical, or has a code that is not a number, or if a numeric column has infinite values that are not special codes.

See also

kivi.spec.fit_spec

Bin and encode the columns chosen after profiling.

kivi.woe.woe_table

The WOE and IV of one grouped column.

kivi.metrics.gini

The Gini coefficient of a score.

kivi.metrics.ks

The KS statistic of a score.

kivi.binning.bin_edges

The quantile edges of the quick binning.

Notes

Every column gets

  • kind: "numeric" or "categorical";

  • count and missing: the number of rows with and without a value, and missing_share, the share of rows without one;

  • distinct: the number of different values;

  • top and top_share: the most frequent value and its share of the rows with a value. Of values that are equally frequent, the first in the order of the categories, or else of appearance, is shown;

  • special and special_share: the number and share of rows with a special code, 0 for categorical columns;

  • mean, std, min, q01, q50, q99 and max: the mean, the sample standard deviation, the smallest value, the 1%, 50% and 99% quantiles and the largest value of a numeric column, without missing values and special codes. Categorical columns get NaN.

The quantiles interpolate linearly, as numpy.quantile does; with weights they are weighted quantiles by the inverted CDF, as the edges of kivi.binning.bin_edges. Weights, even unit weights, therefore change the quantiles and, through the edges, iv, chi2_p_value and tied_bins; with integer weights every other column equals that of the repeated rows without weights. The standard deviation divides by the total weight minus 1, as it divides by the number of rows minus 1 without weights, so it is NaN when the weights of a column’s values sum to 1 or less.

With target, every column also gets

  • event_rate: the event rate of all rows, the same in every row of the table;

  • missing_event_rate and non_missing_event_rate: the event rates of the rows without and with a value, NaN when there are no such rows;

  • missing_lift and non_missing_lift: these rates divided by event_rate, so a lift above 1 marks riskier rows;

  • iv: the information value of the column, summed over the groups of kivi.woe.woe_table. Numeric columns are cut into bins quantile bins with kivi.binning.bin_edges and kivi.binning.cut, with a group for each special code; categorical columns keep their labels. Missing values form a group of their own;

  • tied_bins: True where the quick binning of a numeric column has fewer bins than requested, because tied quantiles were merged or no values are left to bin apart from missing values and special codes. The table records this instead of warning for every column, as kivi.binning.bin_edges does; such an IV understates the column until it is binned with custom edges or special codes;

  • gini: the Gini coefficient of the values of a numeric column as a score, without missing values and special codes. It is positive when events have higher values, negative when they have lower ones, and NaN for categorical columns or when the values leave out a class.

After these, or after max without target, every column gets three statistics of the shape of the distribution, computed from the same values as the summary, without missing values and special codes. Categorical columns get NaN.

  • skewness: the bias-corrected sample skewness \(G_1\), as pandas.Series.skew computes it;

  • kurtosis: the bias-corrected sample excess kurtosis \(G_2\), as pandas.Series.kurt computes it, 0 for a normal distribution;

  • cv: the coefficient of variation std / mean, with the sign of the mean, NaN when the mean is 0.

With \(n\) values \(x_i\), their mean \(\bar x\) and \(M_k = \sum_i (x_i - \bar x)^k\),

\[G_1 = \frac{n \sqrt{n - 1}}{n - 2} \frac{M_3}{M_2^{3/2}}, \qquad G_2 = \frac{n (n + 1) (n - 1)}{(n - 2)(n - 3)} \frac{M_4}{M_2^2} - \frac{3 (n - 1)^2}{(n - 2)(n - 3)}.\]

\(G_1\) is NaN for 2 values or fewer, \(G_2\) for 3 or fewer, and both when all values are equal. With weights, \(n\) is the total weight and every sum is weighted, so integer weights equal repeated rows, and the total weight must exceed 2 and 3.

With target, these are followed by

  • ks: the KS statistic of the same values, the largest gap between the cumulative distributions of the values of events and of non-events, from 0 to 1 whichever way the values run, as kivi.metrics.ks defines it. NaN where gini is NaN;

  • chi2_p_value: the p-value of the chi-squared test of independence between the target and the groups of the quick binning that gives iv, missing values and special codes included. With \(O\) the counts of events and non-events in each of the \(k\) groups and \(E\) the counts expected if the event rate were the same in every group, the statistic \(\sum (O - E)^2 / E\) is compared with a chi-squared distribution with \(k - 1\) degrees of freedom. The p-value is 1 when there is a single group.

The quick binning gives a first ranking, not a final one: an IV from five quantile bins can miss a pattern that other edges would show, and a categorical column with many rare labels gets an inflated IV. The chi-squared test asks only whether the event rate differs between the groups: with thousands of rows a weak relation already gives a p-value close to 0, so rank by iv and read a large p-value as a column with no evidence of a relation. Weights from sampling rates inflate the number of observations and make the p-value too small.

Examples

>>> import pandas as pd
>>> from kivi.univariate import profile_table
>>> frame = pd.DataFrame({
...     "age": [23, 31, None, 52, 38, 27, 61, 49],
...     "housing": ["yes", "no", "yes", "no", "no", "yes", None, "yes"],
... })
>>> profile = profile_table(frame)
>>> profile[["kind", "count", "missing", "distinct", "top", "top_share"]]
                 kind  count  missing  distinct  top  top_share
variable
age           numeric      7        1         7  23.0   0.142857
housing   categorical      7        1         2  yes   0.571429
>>> profile.loc["age", ["min", "q50", "max"]].tolist()
[23.0, 38.0, 61.0]
>>> profile.loc["age", ["skewness", "kurtosis", "cv"]].round(4).tolist()
[0.2736, -1.51, 0.3536]

With a target, the event rates and the separation of each column:

>>> target = pd.Series([1, 0, 1, 0, 1, 1, 0, 0])
>>> profile = profile_table(frame, target, bins=2)
>>> profile[["missing_event_rate", "non_missing_event_rate", "iv", "gini"]].round(4)
          missing_event_rate  non_missing_event_rate      iv    gini
variable
age                      1.0                  0.4286  1.5607 -0.8333
housing                  0.0                  0.5714  0.7466     NaN
>>> profile[["ks", "chi2_p_value"]].round(4)
            ks  chi2_p_value
variable
age       0.75        0.0821
housing    NaN        0.3114