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")
| 5996 | |
| 5997 | |
| 5998 | def pivot_table(df, index, columns, values, aggfunc="mean"): |
| 5999 | """ |
| 6000 | Create a spreadsheet-style pivot table as a DataFrame. Target ``columns`` |
| 6001 | must have category dtype to infer result's ``columns``. |
| 6002 | ``index``, ``columns``, and ``aggfunc`` must be all scalar. |
| 6003 | ``values`` can be scalar or list-like. |
| 6004 | |
| 6005 | Parameters |
| 6006 | ---------- |
| 6007 | df : DataFrame |
| 6008 | index : scalar |
| 6009 | column to be index |
| 6010 | columns : scalar |
| 6011 | column to be columns |
| 6012 | values : scalar or list(scalar) |
| 6013 | column(s) to aggregate |
| 6014 | aggfunc : {'mean', 'sum', 'count', 'first', 'last'}, default 'mean' |
| 6015 | |
| 6016 | Returns |
| 6017 | ------- |
| 6018 | table : DataFrame |
| 6019 | |
| 6020 | See Also |
| 6021 | -------- |
| 6022 | pandas.DataFrame.pivot_table |
| 6023 | """ |
| 6024 | if not is_scalar(index) or index not in df._meta.columns: |
| 6025 | raise ValueError("'index' must be the name of an existing column") |
| 6026 | if not is_scalar(columns) or columns not in df._meta.columns: |
| 6027 | raise ValueError("'columns' must be the name of an existing column") |
| 6028 | if not methods.is_categorical_dtype(df._meta[columns]): |
| 6029 | raise ValueError("'columns' must be category dtype") |
| 6030 | if not has_known_categories(df._meta[columns]): |
| 6031 | raise ValueError("'columns' must have known categories") |
| 6032 | |
| 6033 | if not ( |
| 6034 | is_scalar(values) |
| 6035 | and values in df._meta.columns |
| 6036 | or not is_scalar(values) |
| 6037 | and all(is_scalar(x) and x in df._meta.columns for x in values) |
| 6038 | ): |
| 6039 | raise ValueError("'values' must refer to an existing column or columns") |
| 6040 | |
| 6041 | available_aggfuncs = ["mean", "sum", "count", "first", "last"] |
| 6042 | |
| 6043 | if not is_scalar(aggfunc) or aggfunc not in available_aggfuncs: |
| 6044 | raise ValueError( |
| 6045 | "aggfunc must be either " + ", ".join(f"'{x}'" for x in available_aggfuncs) |
| 6046 | ) |
| 6047 | |
| 6048 | return new_collection( |
| 6049 | PivotTable(df, index=index, columns=columns, values=values, aggfunc=aggfunc) |
| 6050 | ) |
| 6051 | |
| 6052 | |
| 6053 | @derived_from(pd, ua_args=["downcast"]) |