|
| 1 | +""" |
| 2 | +Module responsible for execution of NDFrame.describe() method. |
| 3 | +
|
| 4 | +Method NDFrame.describe() delegates actual execution to function describe_ndframe(). |
| 5 | +""" |
| 6 | + |
| 7 | +from typing import TYPE_CHECKING, List, Optional, Sequence, Union |
| 8 | +import warnings |
| 9 | + |
| 10 | +import numpy as np |
| 11 | + |
| 12 | +from pandas._libs.tslibs import Timestamp |
| 13 | +from pandas._typing import FrameOrSeries, Hashable |
| 14 | +from pandas.util._validators import validate_percentile |
| 15 | + |
| 16 | +from pandas.core.dtypes.common import ( |
| 17 | + is_bool_dtype, |
| 18 | + is_datetime64_any_dtype, |
| 19 | + is_numeric_dtype, |
| 20 | + is_timedelta64_dtype, |
| 21 | +) |
| 22 | + |
| 23 | +from pandas.core.reshape.concat import concat |
| 24 | + |
| 25 | +from pandas.io.formats.format import format_percentiles |
| 26 | + |
| 27 | +if TYPE_CHECKING: |
| 28 | + from pandas import Series |
| 29 | + |
| 30 | + |
| 31 | +def describe_ndframe( |
| 32 | + *, |
| 33 | + obj: FrameOrSeries, |
| 34 | + include: Optional[Union[str, Sequence[str]]], |
| 35 | + exclude: Optional[Union[str, Sequence[str]]], |
| 36 | + datetime_is_numeric: bool, |
| 37 | + percentiles: Optional[Sequence[float]], |
| 38 | +) -> FrameOrSeries: |
| 39 | + """Describe series or dataframe. |
| 40 | +
|
| 41 | + Called from pandas.core.generic.NDFrame.describe() |
| 42 | +
|
| 43 | + Parameters |
| 44 | + ---------- |
| 45 | + obj: DataFrame or Series |
| 46 | + Either dataframe or series to be described. |
| 47 | + include : 'all', list-like of dtypes or None (default), optional |
| 48 | + A white list of data types to include in the result. Ignored for ``Series``. |
| 49 | + exclude : list-like of dtypes or None (default), optional, |
| 50 | + A black list of data types to omit from the result. Ignored for ``Series``. |
| 51 | + datetime_is_numeric : bool, default False |
| 52 | + Whether to treat datetime dtypes as numeric. |
| 53 | + percentiles : list-like of numbers, optional |
| 54 | + The percentiles to include in the output. All should fall between 0 and 1. |
| 55 | + The default is ``[.25, .5, .75]``, which returns the 25th, 50th, and |
| 56 | + 75th percentiles. |
| 57 | +
|
| 58 | + Returns |
| 59 | + ------- |
| 60 | + Dataframe or series description. |
| 61 | + """ |
| 62 | + if obj.ndim == 2 and obj.columns.size == 0: |
| 63 | + raise ValueError("Cannot describe a DataFrame without columns") |
| 64 | + |
| 65 | + if percentiles is not None: |
| 66 | + # explicit conversion of `percentiles` to list |
| 67 | + percentiles = list(percentiles) |
| 68 | + |
| 69 | + # get them all to be in [0, 1] |
| 70 | + validate_percentile(percentiles) |
| 71 | + |
| 72 | + # median should always be included |
| 73 | + if 0.5 not in percentiles: |
| 74 | + percentiles.append(0.5) |
| 75 | + percentiles = np.asarray(percentiles) |
| 76 | + else: |
| 77 | + percentiles = np.array([0.25, 0.5, 0.75]) |
| 78 | + |
| 79 | + # sort and check for duplicates |
| 80 | + unique_pcts = np.unique(percentiles) |
| 81 | + assert percentiles is not None |
| 82 | + if len(unique_pcts) < len(percentiles): |
| 83 | + raise ValueError("percentiles cannot contain duplicates") |
| 84 | + percentiles = unique_pcts |
| 85 | + |
| 86 | + formatted_percentiles = format_percentiles(percentiles) |
| 87 | + |
| 88 | + def describe_numeric_1d(series) -> "Series": |
| 89 | + from pandas import Series |
| 90 | + |
| 91 | + stat_index = ["count", "mean", "std", "min"] + formatted_percentiles + ["max"] |
| 92 | + d = ( |
| 93 | + [series.count(), series.mean(), series.std(), series.min()] |
| 94 | + + series.quantile(percentiles).tolist() |
| 95 | + + [series.max()] |
| 96 | + ) |
| 97 | + return Series(d, index=stat_index, name=series.name) |
| 98 | + |
| 99 | + def describe_categorical_1d(data) -> "Series": |
| 100 | + names = ["count", "unique"] |
| 101 | + objcounts = data.value_counts() |
| 102 | + count_unique = len(objcounts[objcounts != 0]) |
| 103 | + result = [data.count(), count_unique] |
| 104 | + dtype = None |
| 105 | + if result[1] > 0: |
| 106 | + top, freq = objcounts.index[0], objcounts.iloc[0] |
| 107 | + if is_datetime64_any_dtype(data.dtype): |
| 108 | + if obj.ndim == 1: |
| 109 | + stacklevel = 5 |
| 110 | + else: |
| 111 | + stacklevel = 6 |
| 112 | + warnings.warn( |
| 113 | + "Treating datetime data as categorical rather than numeric in " |
| 114 | + "`.describe` is deprecated and will be removed in a future " |
| 115 | + "version of pandas. Specify `datetime_is_numeric=True` to " |
| 116 | + "silence this warning and adopt the future behavior now.", |
| 117 | + FutureWarning, |
| 118 | + stacklevel=stacklevel, |
| 119 | + ) |
| 120 | + tz = data.dt.tz |
| 121 | + asint = data.dropna().values.view("i8") |
| 122 | + top = Timestamp(top) |
| 123 | + if top.tzinfo is not None and tz is not None: |
| 124 | + # Don't tz_localize(None) if key is already tz-aware |
| 125 | + top = top.tz_convert(tz) |
| 126 | + else: |
| 127 | + top = top.tz_localize(tz) |
| 128 | + names += ["top", "freq", "first", "last"] |
| 129 | + result += [ |
| 130 | + top, |
| 131 | + freq, |
| 132 | + Timestamp(asint.min(), tz=tz), |
| 133 | + Timestamp(asint.max(), tz=tz), |
| 134 | + ] |
| 135 | + else: |
| 136 | + names += ["top", "freq"] |
| 137 | + result += [top, freq] |
| 138 | + |
| 139 | + # If the DataFrame is empty, set 'top' and 'freq' to None |
| 140 | + # to maintain output shape consistency |
| 141 | + else: |
| 142 | + names += ["top", "freq"] |
| 143 | + result += [np.nan, np.nan] |
| 144 | + dtype = "object" |
| 145 | + |
| 146 | + from pandas import Series |
| 147 | + |
| 148 | + return Series(result, index=names, name=data.name, dtype=dtype) |
| 149 | + |
| 150 | + def describe_timestamp_1d(data) -> "Series": |
| 151 | + # GH-30164 |
| 152 | + from pandas import Series |
| 153 | + |
| 154 | + stat_index = ["count", "mean", "min"] + formatted_percentiles + ["max"] |
| 155 | + d = ( |
| 156 | + [data.count(), data.mean(), data.min()] |
| 157 | + + data.quantile(percentiles).tolist() |
| 158 | + + [data.max()] |
| 159 | + ) |
| 160 | + return Series(d, index=stat_index, name=data.name) |
| 161 | + |
| 162 | + def describe_1d(data) -> "Series": |
| 163 | + if is_bool_dtype(data.dtype): |
| 164 | + return describe_categorical_1d(data) |
| 165 | + elif is_numeric_dtype(data): |
| 166 | + return describe_numeric_1d(data) |
| 167 | + elif is_datetime64_any_dtype(data.dtype) and datetime_is_numeric: |
| 168 | + return describe_timestamp_1d(data) |
| 169 | + elif is_timedelta64_dtype(data.dtype): |
| 170 | + return describe_numeric_1d(data) |
| 171 | + else: |
| 172 | + return describe_categorical_1d(data) |
| 173 | + |
| 174 | + if obj.ndim == 1: |
| 175 | + # Incompatible return value type |
| 176 | + # (got "Series", expected "FrameOrSeries") [return-value] |
| 177 | + return describe_1d(obj) # type:ignore[return-value] |
| 178 | + elif (include is None) and (exclude is None): |
| 179 | + # when some numerics are found, keep only numerics |
| 180 | + default_include = [np.number] |
| 181 | + if datetime_is_numeric: |
| 182 | + default_include.append("datetime") |
| 183 | + data = obj.select_dtypes(include=default_include) |
| 184 | + if len(data.columns) == 0: |
| 185 | + data = obj |
| 186 | + elif include == "all": |
| 187 | + if exclude is not None: |
| 188 | + msg = "exclude must be None when include is 'all'" |
| 189 | + raise ValueError(msg) |
| 190 | + data = obj |
| 191 | + else: |
| 192 | + data = obj.select_dtypes(include=include, exclude=exclude) |
| 193 | + |
| 194 | + ldesc = [describe_1d(s) for _, s in data.items()] |
| 195 | + # set a convenient order for rows |
| 196 | + names: List[Hashable] = [] |
| 197 | + ldesc_indexes = sorted((x.index for x in ldesc), key=len) |
| 198 | + for idxnames in ldesc_indexes: |
| 199 | + for name in idxnames: |
| 200 | + if name not in names: |
| 201 | + names.append(name) |
| 202 | + |
| 203 | + d = concat([x.reindex(names, copy=False) for x in ldesc], axis=1, sort=False) |
| 204 | + d.columns = data.columns.copy() |
| 205 | + return d |
0 commit comments