You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by GitBox <gi...@apache.org> on 2022/09/21 00:27:12 UTC

[GitHub] [spark] itholic commented on a diff in pull request #37923: [SPARK-40334][PS] Implement `GroupBy.prod`

itholic commented on code in PR #37923:
URL: https://github.com/apache/spark/pull/37923#discussion_r975910504


##########
python/pyspark/pandas/groupby.py:
##########
@@ -993,6 +993,105 @@ def nth(self, n: int) -> FrameLike:
 
         return self._prepare_return(DataFrame(internal))
 
+    def prod(self, numeric_only: Optional[bool] = True, min_count: int = 0) -> FrameLike:
+        """
+        Compute prod of groups.
+
+        .. versionadded:: 3.4.0
+
+        Parameters
+        ----------
+        numeric_only : bool, default False
+            Include only float, int, boolean columns. If None, will attempt to use
+            everything, then use only numeric data.
+
+        min_count: int, default 0
+            The required number of valid values to perform the operation.
+            If fewer than min_count non-NA values are present the result will be NA.
+
+        Returns
+        -------
+        Series or DataFrame
+
+        See Also
+        --------
+        pyspark.pandas.Series.groupby
+        pyspark.pandas.DataFrame.groupby
+
+        Examples
+        --------
+        >>> df = ps.DataFrame({'A': [1, 1, 2, 1, 2],
+        ...                    'B': [np.nan, 2, 3, 4, 5],
+        ...                    'C': [1, 2, 1, 1, 2],
+        ...                    'D': [True, False, True, False, True]})

Review Comment:
   nit: formatting
   
   
   ```suggestion
           >>> df = ps.DataFrame(
           ...     {
           ...         "A": [1, 1, 2, 1, 2],
           ...         "B": [np.nan, 2, 3, 4, 5],
           ...         "C": [1, 2, 1, 1, 2],
           ...         "D": [True, False, True, False, True],
           ...     }
           ... )
   ```



##########
python/pyspark/pandas/groupby.py:
##########
@@ -993,6 +993,105 @@ def nth(self, n: int) -> FrameLike:
 
         return self._prepare_return(DataFrame(internal))
 
+    def prod(self, numeric_only: Optional[bool] = True, min_count: int = 0) -> FrameLike:
+        """
+        Compute prod of groups.
+
+        .. versionadded:: 3.4.0
+
+        Parameters
+        ----------
+        numeric_only : bool, default False
+            Include only float, int, boolean columns. If None, will attempt to use
+            everything, then use only numeric data.
+
+        min_count: int, default 0
+            The required number of valid values to perform the operation.
+            If fewer than min_count non-NA values are present the result will be NA.
+
+        Returns
+        -------
+        Series or DataFrame
+
+        See Also
+        --------
+        pyspark.pandas.Series.groupby
+        pyspark.pandas.DataFrame.groupby
+
+        Examples
+        --------
+        >>> df = ps.DataFrame({'A': [1, 1, 2, 1, 2],
+        ...                    'B': [np.nan, 2, 3, 4, 5],
+        ...                    'C': [1, 2, 1, 1, 2],
+        ...                    'D': [True, False, True, False, True]})
+
+        Groupby one column and return the prod of the remaining columns in
+        each group.
+
+        >>> df.groupby('A').prod().sort_index()
+             B  C  D
+        A
+        1  8.0  2  0
+        2  15.0 2  1
+
+        >>> df.groupby('A').prod(min_count=3).sort_index()
+             B  C   D
+        A
+        1  NaN  2.0  0.0
+        2  NaN NaN  NaN
+        """
+
+        self._validate_agg_columns(numeric_only=numeric_only, function_name="prod")
+
+        groupkey_names = [SPARK_INDEX_NAME_FORMAT(i) for i in range(len(self._groupkeys))]
+        internal, agg_columns, sdf = self._prepare_reduce(
+            groupkey_names=groupkey_names,
+            accepted_spark_types=(NumericType, BooleanType),
+            bool_to_numeric=True,
+        )
+
+        psdf: DataFrame = DataFrame(internal)
+        if len(psdf._internal.column_labels) > 0:
+
+            stat_exprs = []
+            for label in psdf._internal.column_labels:
+                tmp_count_column = verify_temp_column_name(sdf, "__tmp_%s_count_col__" % label[0])
+                psser = psdf._psser_for(label)
+                column = psser._dtype_op.nan_to_null(psser).spark.column
+                data_type = psser.spark.data_type
+
+                if isinstance(data_type, IntegralType):
+                    stat_exprs.append(F.product(column).cast(data_type).alias(label[0]))
+                else:
+                    stat_exprs.append(F.product(column).alias(label[0]))

Review Comment:
   What about defining a `label[0]` as a variable since it's used in multiple places ?



##########
python/pyspark/pandas/groupby.py:
##########
@@ -993,6 +993,105 @@ def nth(self, n: int) -> FrameLike:
 
         return self._prepare_return(DataFrame(internal))
 
+    def prod(self, numeric_only: Optional[bool] = True, min_count: int = 0) -> FrameLike:
+        """
+        Compute prod of groups.
+
+        .. versionadded:: 3.4.0
+
+        Parameters
+        ----------
+        numeric_only : bool, default False
+            Include only float, int, boolean columns. If None, will attempt to use
+            everything, then use only numeric data.
+
+        min_count: int, default 0
+            The required number of valid values to perform the operation.
+            If fewer than min_count non-NA values are present the result will be NA.
+
+        Returns
+        -------
+        Series or DataFrame
+
+        See Also
+        --------
+        pyspark.pandas.Series.groupby
+        pyspark.pandas.DataFrame.groupby
+
+        Examples
+        --------
+        >>> df = ps.DataFrame({'A': [1, 1, 2, 1, 2],
+        ...                    'B': [np.nan, 2, 3, 4, 5],
+        ...                    'C': [1, 2, 1, 1, 2],
+        ...                    'D': [True, False, True, False, True]})
+
+        Groupby one column and return the prod of the remaining columns in
+        each group.
+
+        >>> df.groupby('A').prod().sort_index()
+             B  C  D
+        A
+        1  8.0  2  0
+        2  15.0 2  1
+
+        >>> df.groupby('A').prod(min_count=3).sort_index()
+             B  C   D
+        A
+        1  NaN  2.0  0.0
+        2  NaN NaN  NaN
+        """
+
+        self._validate_agg_columns(numeric_only=numeric_only, function_name="prod")
+
+        groupkey_names = [SPARK_INDEX_NAME_FORMAT(i) for i in range(len(self._groupkeys))]
+        internal, agg_columns, sdf = self._prepare_reduce(
+            groupkey_names=groupkey_names,
+            accepted_spark_types=(NumericType, BooleanType),
+            bool_to_numeric=True,
+        )
+
+        psdf: DataFrame = DataFrame(internal)
+        if len(psdf._internal.column_labels) > 0:
+
+            stat_exprs = []
+            for label in psdf._internal.column_labels:
+                tmp_count_column = verify_temp_column_name(sdf, "__tmp_%s_count_col__" % label[0])
+                psser = psdf._psser_for(label)
+                column = psser._dtype_op.nan_to_null(psser).spark.column
+                data_type = psser.spark.data_type
+
+                if isinstance(data_type, IntegralType):
+                    stat_exprs.append(F.product(column).cast(data_type).alias(label[0]))
+                else:
+                    stat_exprs.append(F.product(column).alias(label[0]))
+
+                if min_count > 0:
+                    stat_exprs.append(F.count(column).alias(tmp_count_column))
+
+            sdf = sdf.groupby(*groupkey_names).agg(*stat_exprs)
+
+            if min_count > 0:
+                for label in psdf._internal.column_labels:
+                    tmp_count_column = "__tmp_%s_count_col__"
+                    sdf = sdf.withColumn(
+                        label[0],
+                        F.when(
+                            F.col(tmp_count_column % label[0]).__ge__(min_count), F.col(label[0])

Review Comment:
   ditto ?



##########
python/pyspark/pandas/groupby.py:
##########
@@ -993,6 +993,105 @@ def nth(self, n: int) -> FrameLike:
 
         return self._prepare_return(DataFrame(internal))
 
+    def prod(self, numeric_only: Optional[bool] = True, min_count: int = 0) -> FrameLike:
+        """
+        Compute prod of groups.
+
+        .. versionadded:: 3.4.0
+
+        Parameters
+        ----------
+        numeric_only : bool, default False
+            Include only float, int, boolean columns. If None, will attempt to use
+            everything, then use only numeric data.
+
+        min_count: int, default 0
+            The required number of valid values to perform the operation.
+            If fewer than min_count non-NA values are present the result will be NA.
+
+        Returns
+        -------
+        Series or DataFrame

Review Comment:
   Let's add a sub-description as pandas does.
   
   ```suggestion
           Series or DataFrame
               Computed prod of values within each group.
   ```



##########
python/pyspark/pandas/groupby.py:
##########
@@ -1052,10 +1052,10 @@ def prod(self, numeric_only: Optional[bool] = True, min_count: int = 0) -> Frame
 
         psdf: DataFrame = DataFrame(internal)
         if len(psdf._internal.column_labels) > 0:
-            tmp_count_column = verify_temp_column_name(psdf, "__tmp_%s_count_col__")
 
             stat_exprs = []
             for label in psdf._internal.column_labels:
+                tmp_count_column = verify_temp_column_name(sdf, "__tmp_%s_count_col__" % label[0])

Review Comment:
   nit: use `tmp_count_column_name` instead to make it more explicit ?



-- 
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.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org