zhengruifeng commented on code in PR #37978:
URL: https://github.com/apache/spark/pull/37978#discussion_r979482634
##
python/pyspark/pandas/series.py:
##
@@ -6610,6 +6610,78 @@ def compare(
)
return DataFrame(internal)
+# todo: 1, support array-like 'value'; 2, add parameter 'sorter'
+def searchsorted(self, value: Any, side: str = "left") -> int:
+"""
+Find indices where elements should be inserted to maintain order.
+
+Find the indices into a sorted Series self such that, if the
corresponding elements
+in value were inserted before the indices, the order of self would be
preserved.
+
+Parameters
+--
+value : scalar
+Values to insert into self.
+side : {‘left’, ‘right’}, optional
+If ‘left’, the index of the first suitable location found is given.
+If ‘right’, return the last such index. If there is no suitable
index,
+return either 0 or N (where N is the length of self).
+
+Returns
+---
+int
+insertion point
+
+Notes
+-
+The Series must be monotonically sorted, otherwise wrong locations
will likely be returned.
+
+Examples
+
+>>> ser = ps.Series([1, 2, 2, 3])
+>>> ser.searchsorted(0)
+0
+>>> ser.searchsorted(1)
+0
+>>> ser.searchsorted(2)
+1
+>>> ser.searchsorted(5)
+4
+>>> ser.searchsorted(0, side="right")
+0
+>>> ser.searchsorted(1, side="right")
+1
+>>> ser.searchsorted(2, side="right")
+3
+>>> ser.searchsorted(5, side="right")
+4
+"""
+if side not in ["left", "right"]:
+raise ValueError(f"Invalid side {side}")
+
+sdf = self._internal.spark_frame
+index_col_name = verify_temp_column_name(sdf,
"__search_sorted_index_col__")
+value_col_name = verify_temp_column_name(sdf,
"__search_sorted_value_col__")
+sdf = InternalFrame.attach_distributed_sequence_column(
+sdf.select(self.spark.column.alias(value_col_name)), index_col_name
+)
+
+if side == "left":
+results = sdf.select(
+F.min(F.when(F.lit(value) <= F.col(value_col_name),
F.col(index_col_name))),
+F.count(F.lit(0)),
+).take(1)
+else:
+results = sdf.select(
+F.min(F.when(F.lit(value) < F.col(value_col_name),
F.col(index_col_name))),
+F.count(F.lit(0)),
+).take(1)
Review Comment:
```
In [5]: ser = pd.Series([])
:1: FutureWarning: The default dtype for empty
Series will be 'object' instead of 'float64' in a future version. Specify a
dtype explicitly to silence this warning.
ser = pd.Series([])
In [6]: ser.searchsorted(5, 'right')
Out[6]: 0
```
`Series.searchsorted` works with empty series, so here should use `take`
instead of `first` which will raise an exception.
Let me add a test case for empty series
--
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-unsubscr...@spark.apache.org
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org
-
To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org
For additional commands, e-mail: reviews-h...@spark.apache.org