xinrong-databricks commented on code in PR #36464:
URL: https://github.com/apache/spark/pull/36464#discussion_r869458670


##########
python/pyspark/pandas/groupby.py:
##########
@@ -2121,11 +2121,22 @@ def _limit(self, n: int, asc: bool) -> FrameLike:
             )
         )
 
-        sdf = (
-            sdf.withColumn(tmp_col, F.row_number().over(window))
-            .filter(F.col(tmp_col) <= n)
-            .drop(tmp_col)
-        )
+        if n >= 0 or LooseVersion(pd.__version__) < LooseVersion("1.4.0"):
+            sdf = (
+                sdf.withColumn(tmp_row_num_col, F.row_number().over(window))
+                .filter(F.col(tmp_row_num_col) <= n)
+                .drop(tmp_row_num_col)
+            )
+        else:
+            # Pandas supports Groupby positional indexing since v1.4.0
+            # 
https://pandas.pydata.org/docs/whatsnew/v1.4.0.html#groupby-positional-indexing
+            tmp_cnt_col = verify_temp_column_name(sdf, "__group_count__")
+            sdf = (
+                sdf.withColumn(tmp_row_num_col, F.row_number().over(window))
+                .withColumn(tmp_cnt_col, 
F.count("*").over(Window.partitionBy(*groupkey_scols)))
+                .filter(F.col(tmp_row_num_col) - F.col(tmp_cnt_col) <= n)

Review Comment:
   The filter condition is cool but may not be easy to understand. Shall we add 
(an example as?) a comment?



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to