Create a spreadsheet-style pivot table as a DataFrame. Target ``columns`` must have category dtype to infer result's ``columns``. ``index``, ``columns``, and ``aggfunc`` must be all scalar. ``values`` can be scalar or list-like. Parameters ---------- df : DataFrame
(df, index, columns, values, aggfunc="mean")
| 6035 | |
| 6036 | |
| 6037 | def pivot_table(df, index, columns, values, aggfunc="mean"): |
| 6038 | """ |
| 6039 | Create a spreadsheet-style pivot table as a DataFrame. Target ``columns`` |
| 6040 | must have category dtype to infer result's ``columns``. |
| 6041 | ``index``, ``columns``, and ``aggfunc`` must be all scalar. |
| 6042 | ``values`` can be scalar or list-like. |
| 6043 | |
| 6044 | Parameters |
| 6045 | ---------- |
| 6046 | df : DataFrame |
| 6047 | index : scalar |
| 6048 | column to be index |
| 6049 | columns : scalar |
| 6050 | column to be columns |
| 6051 | values : scalar or list(scalar) |
| 6052 | column(s) to aggregate |
| 6053 | aggfunc : {'mean', 'sum', 'count', 'first', 'last'}, default 'mean' |
| 6054 | |
| 6055 | Returns |
| 6056 | ------- |
| 6057 | table : DataFrame |
| 6058 | |
| 6059 | See Also |
| 6060 | -------- |
| 6061 | pandas.DataFrame.pivot_table |
| 6062 | """ |
| 6063 | if not is_scalar(index) or index not in df._meta.columns: |
| 6064 | raise ValueError("'index' must be the name of an existing column") |
| 6065 | if not is_scalar(columns) or columns not in df._meta.columns: |
| 6066 | raise ValueError("'columns' must be the name of an existing column") |
| 6067 | if not methods.is_categorical_dtype(df._meta[columns]): |
| 6068 | raise ValueError("'columns' must be category dtype") |
| 6069 | if not has_known_categories(df._meta[columns]): |
| 6070 | raise ValueError("'columns' must have known categories") |
| 6071 | |
| 6072 | if not ( |
| 6073 | is_scalar(values) |
| 6074 | and values in df._meta.columns |
| 6075 | or not is_scalar(values) |
| 6076 | and all(is_scalar(x) and x in df._meta.columns for x in values) |
| 6077 | ): |
| 6078 | raise ValueError("'values' must refer to an existing column or columns") |
| 6079 | |
| 6080 | available_aggfuncs = ["mean", "sum", "count", "first", "last"] |
| 6081 | |
| 6082 | if not is_scalar(aggfunc) or aggfunc not in available_aggfuncs: |
| 6083 | raise ValueError( |
| 6084 | "aggfunc must be either " + ", ".join(f"'{x}'" for x in available_aggfuncs) |
| 6085 | ) |
| 6086 | |
| 6087 | return new_collection( |
| 6088 | PivotTable(df, index=index, columns=columns, values=values, aggfunc=aggfunc) |
| 6089 | ) |
| 6090 | |
| 6091 | |
| 6092 | @derived_from(pd, ua_args=["downcast"]) |