dpgaspar commented on a change in pull request #9427: feat: Add post processing 
to QueryObject
URL: 
https://github.com/apache/incubator-superset/pull/9427#discussion_r405385395
 
 

 ##########
 File path: superset/utils/pandas_postprocessing.py
 ##########
 @@ -0,0 +1,268 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from functools import partial
+from typing import Any, Dict, List, Optional, Union
+
+import numpy as np
+from flask_babel import gettext as _
+from pandas import DataFrame, NamedAgg
+
+from superset.exceptions import SupersetException
+
+SUPPORTED_NUMPY_FUNCTIONS = (
+    "average",
+    "argmin",
+    "argmax",
+    "cumsum",
+    "cumprod",
+    "max",
+    "mean",
+    "median",
+    "nansum" "nanmin" "nanmax" "nanmean",
+    "nanmedian",
+    "min",
+    "percentile",
+    "prod",
+    "product",
+    "std",
+    "sum",
+    "var",
+)
+
+
+def _get_aggregate_funcs(aggregates: Dict[str, Dict[str, Any]],) -> Dict[str, 
NamedAgg]:
+    """
+    Converts a set of aggregate config objects into functions that pandas can 
use as
+    aggregators. Currently only numpy aggregators are supported.
+
+    :param aggregates: Mapping from column name to aggregat config.
+    :return: Mapping from metric name to function that takes a single input 
argument.
+    """
+    agg_funcs: Dict[str, NamedAgg] = {}
+    for name, agg_obj in aggregates.items():
+        column = agg_obj.get("column", name)
+        operator = agg_obj.get("operator") or "sum"
+        if operator not in SUPPORTED_NUMPY_FUNCTIONS:
+            raise SupersetException("Unsupported numpy function: %")
+        func = getattr(np, operator)
+        options = agg_obj.get("options", {})
+        agg_funcs[name] = NamedAgg(column=column, aggfunc=partial(func, 
**options))
+
+    return agg_funcs
+
+
+def _append_columns(
+    base_df: DataFrame, append_df: DataFrame, columns: Dict[str, str]
+) -> DataFrame:
+    """
+    Function for adding columns from one DataFrame to another DataFrame. Calls 
the
+    assign method, which overwrites the original column in `base_df` if the 
column
+    already exists, and appends the column if the name is not defined.
+
+    :param base_df: DataFrame which to use as the base
+    :param append_df: DataFrame from which to select data.
+    :param columns: columns on which to append, mapping source column to
+           target column. For instance, `{'y': 'y'}` will replace the values in
+           column `y` in `base_df` with the values in `y` in `append_df`,
+           while `{'y': 'y2'}` will add a column `y2` to `base_df` based
+           on values in column `y` in `append_df`, leaving the original column 
`y`
+           in `base_df` unchanged.
+    :return: new DataFrame with combined data from `base_df` and `append_df`
+    """
+    return base_df.assign(
+        **{
+            target: append_df[append_df.columns[idx]]
+            for idx, target in enumerate(columns.values())
+        }
+    )
+
+
+def pivot(
+    df: DataFrame,
+    index: List[str],
+    columns: List[str],
+    aggregates: Dict[str, Dict[str, Any]],
+    metric_fill_value: Optional[Any] = None,
+    column_fill_value: Optional[str] = None,
+    drop_missing_columns: Optional[bool] = True,
+    combine_value_with_metric=False,
+    marginal_distributions: Optional[bool] = None,
+    marginal_distribution_name: Optional[str] = None,
+) -> DataFrame:
+    """
+    Perform a pivot operation on a DataFrame.
+
+    :param df: Object on which pivot operation will be performed
+    :param index: Columns to group by on the table index (=rows)
+    :param columns: Columns to group by on the table columns
+    :param metric_fill_value: Value to replace missing values with
+    :param column_fill_value: Value to replace missing pivot columns with
+    :param drop_missing_columns: Do not include columns whose entries are all 
missing
+    :param combine_value_with_metric: Display metrics side by side within each 
column,
+           as opposed to each column being displayed side by side for each 
metric.
+    :param aggregates: A mapping from aggregate column name to the the 
aggregate
+           config.
+    :param marginal_distributions: Add totals for row/column. Default to False
+    :param marginal_distribution_name: Name of row/column with marginal 
distribution.
+           Default to 'All'.
+    :return: A pivot table
 
 Review comment:
   nit: Add `raises:`

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to