ueshin commented on code in PR #54044:
URL: https://github.com/apache/spark/pull/54044#discussion_r2819766059
##########
python/pyspark/pandas/frame.py:
##########
@@ -12215,23 +12223,76 @@ def idxmax(self, axis: Axis = 0) -> "Series":
c z 2
dtype: int64
"""
- max_cols = map(lambda scol: F.max(scol),
self._internal.data_spark_columns)
- sdf_max = self._internal.spark_frame.select(*max_cols).head()
- # `sdf_max` looks like below
- # +------+------+------+
- # |(a, x)|(b, y)|(c, z)|
- # +------+------+------+
- # | 3| 4.0| 400|
- # +------+------+------+
+ axis = validate_axis(axis)
+ if axis == 0:
+ max_cols = map(lambda scol: F.max(scol),
self._internal.data_spark_columns)
+ sdf_max = self._internal.spark_frame.select(*max_cols).head()
+ # `sdf_max` looks like below
+ # +------+------+------+
+ # |(a, x)|(b, y)|(c, z)|
+ # +------+------+------+
+ # | 3| 4.0| 400|
+ # +------+------+------+
+
+ conds = (
+ scol == max_val for scol, max_val in
zip(self._internal.data_spark_columns, sdf_max)
+ )
+ cond = reduce(lambda x, y: x | y, conds)
- conds = (
- scol == max_val for scol, max_val in
zip(self._internal.data_spark_columns, sdf_max)
- )
- cond = reduce(lambda x, y: x | y, conds)
+ psdf: DataFrame = DataFrame(self._internal.with_filter(cond))
- psdf: DataFrame = DataFrame(self._internal.with_filter(cond))
+ return cast(ps.Series,
ps.from_pandas(psdf._to_internal_pandas().idxmax()))
+ else:
+ from pyspark.pandas.series import first_series
+
+ column_labels = self._internal.column_labels
+
+ if len(column_labels) == 0:
+ return ps.Series([], dtype=np.int64)
+
+ if self._internal.column_labels_level > 1:
+ raise NotImplementedError(
+ "idxmax with axis=1 does not support MultiIndex columns
yet"
+ )
+
+ max_value = F.greatest(
+ *[
+ F.coalesce(self._internal.spark_column_for(label),
F.lit(float("-inf")))
+ for label in column_labels
+ ],
+ F.lit(float("-inf")),
+ )
+
+ result = None
+ for label in reversed(column_labels):
+ scol = self._internal.spark_column_for(label)
+ label_value = label[0] if len(label) == 1 else label
+ condition = (scol == max_value) & scol.isNotNull()
+
+ result = (
+ F.when(condition, F.lit(label_value))
+ if result is None
+ else F.when(condition,
F.lit(label_value)).otherwise(result)
+ )
+
+ result = F.when(max_value == float("-inf"),
F.lit(None)).otherwise(result)
+
+ sdf = self._internal.spark_frame.select(
Review Comment:
We shouldn't create a new Spark DataFrame here to keep the anchor same?
We can use `self._internal.with_new_columns` instead?
--
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]