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/01/13 09:52:58 UTC

[GitHub] [spark] pralabhkumar opened a new pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

pralabhkumar opened a new pull request #35191:
URL: https://github.com/apache/spark/pull/35191


   ### What changes were proposed in this pull request?
   Fix Series.asof when values of the series is not sorted
   
   
   ```
   import pandas as pd
   from pyspark import pandas as ps
   import numpy as np
   pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
   psser = ps.from_pandas(pser)
   psser.asof([5, 25])
   5     NaN
   25    1.0
   Name: Koalas, dtype: float64
   pser.asof([5, 25])
   5     NaN
   25    1.0
   Name: Koalas, dtype: float64
   
   ```
   
   ### Why are the changes needed?
   There is a bug in ps.as_of, when the series is not sorted
   
   ### Does this PR introduce any user-facing change?
   Yes user will be able to see the behavior exactly matching to pandas
   
   ### How was this patch tested?
   unit tests


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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1056765734


   @itholic Please review the changes


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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r821299923



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [last_index if x is np.nan else x for x in where]
+        else:
+            modified_where = where
+
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.last(

Review comment:
       @ueshin  According to https://github.com/apache/spark/pull/35191#discussion_r799222433 . Last is being used , since assumption was dataframe is sorted on index_level_0 .  IF that assumption is not valid , then we cannot use Last . 
   
   cc @itholic 
   




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r819963544



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5241,9 +5253,16 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
 
         # The data is expected to be small so it's fine to transpose/use default index.
         with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
-            psdf: DataFrame = DataFrame(sdf)
-            psdf.columns = pd.Index(where)
-            return first_series(psdf.transpose()).rename(self.name)
+            if len(where) == len(set(where)) and not isinstance(index_type, TimestampType):
+                psdf: DataFrame = DataFrame(sdf)
+                psdf.columns = pd.Index(where)
+                return first_series(psdf.transpose()).rename(self.name)
+            else:
+                # If `where` has duplicate items, leverage the pandas directly

Review comment:
       Yeah, this is because pandas API on Spark doesn't support the duplicated column name.
   
   We use the transform for creating result DataFrame after assigning the column which created by using `where`.
   
   So, we can just say like:
   # If `where` has duplicate items, leverage the pandas directly
   # since pandas API on Spark doesn't support the duplicated column name.




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


[GitHub] [spark] ueshin commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
ueshin commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1065369288


   @pralabhkumar I think it's already fixed. Could you merge the latest master branch and push the commit?


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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r798221462



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       I think maybe we can use `F.last` with `ignorenulls=True` instead of `F.max` ??
   (https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.functions.last.html)
   
   e.g.
   ```python
           cond = [
               F.last(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column), ignorenulls=True)
               for index in where
       ]
   ```
   
   It returns the last non-null value from given column.
   
   If this works, I think we simply need to fix only this part.




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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1047039281


   @itholic , please review the PR . 


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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1017182630


   @HyukjinKwon  Thx for the comments , working on it 


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


[GitHub] [spark] ueshin commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
ueshin commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r821071781



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]

Review comment:
       I guess we can handle `np.nan` in `where` when creating the `cond` below?
   We can pass the original col instead of `F.when( ... )` if it's `np.nan`?




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


[GitHub] [spark] ueshin edited a comment on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
ueshin edited a comment on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1065369288


   @pralabhkumar I think it's already fixed at https://github.com/apache/spark/commit/54abb85aa303b9ccca9a127b45f53e2acc5de438. Could you merge the latest master branch and push the commit?


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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1066595745


   @ueshin 
   Build is passing . please find some time review it . 


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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r788379590



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,62 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+        from pyspark.sql.functions import struct, lit, explode, col, row_number
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                struct(
+                    lit(column_prefix_constant + str(index)).alias("identifier"),
+                    self.spark.column.alias("Koalas"),

Review comment:
       Should we have to use alias here, instead of just use the existing column name ??
   
   At least, the alias "Koalas" looks a bit wired here to me.




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r801233985



##########
File path: python/pyspark/pandas/tests/test_series.py
##########
@@ -2071,6 +2071,22 @@ def test_asof(self):
         with ps.option_context("compute.eager_check", False):
             self.assert_eq(psser.asof(20), 4.0)
 
+        pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 20]), pser.asof([5, 20]))
+
+        pser = pd.Series([4, np.nan, np.nan, 2], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 100]), pser.asof([5, 100]))
+
+        pser = pd.Series([np.nan, 4, 1, 2], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 35]), pser.asof([5, 35]))
+
+        pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([25, 25]), pser.asof([25, 25]))

Review comment:
       Can we also test the string & timestamp index ??
   
   e.g.
   ```python
   >>> pser = pd.Series([2, 1, np.nan, 4], index=['a', 'b', 'c', 'd'])
   >>> pser.asof(['a', 'd'])
   a    2.0
   d    4.0
   dtype: float64
   ```
   
   ```python
   >>> pser = pd.Series([2, 1, np.nan, 4], index=[pd.Timestamp(2020, 1, 1), pd.Timestamp(2020, 2, 2), pd.Timestamp(2020, 3, 3), pd.Timestamp(2020, 4, 4)])
   >>> pser.asof([pd.Timestamp(2020, 1, 1), pd.Timestamp(2020, 2, 4)])
   2020-01-01    2.0
   2020-02-04    1.0
   dtype: float64
   ```

##########
File path: python/pyspark/pandas/tests/test_series.py
##########
@@ -2071,6 +2071,22 @@ def test_asof(self):
         with ps.option_context("compute.eager_check", False):
             self.assert_eq(psser.asof(20), 4.0)
 
+        pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 20]), pser.asof([5, 20]))
+
+        pser = pd.Series([4, np.nan, np.nan, 2], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 100]), pser.asof([5, 100]))
+
+        pser = pd.Series([np.nan, 4, 1, 2], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 35]), pser.asof([5, 35]))
+
+        pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([25, 25]), pser.asof([25, 25]))

Review comment:
       And also set the `np.nan` as `where` ?
   
   ```python
   >>> pser.asof([np.nan, np.nan])
   NaN    3.0
   NaN    3.0
   dtype: float64
   ```
   
   Seems like this case is only supported for numeric type index.




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r800269304



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       I think we might want to return the pandas-on-Spark Series rather than pandas Series, and should leverage the pandas `Series` directly when only the `where` has duplicate item. (and seems like `column_prefix_constant` is not necessary?)
   
   So, how about this ??
   
   ```python
           cond = [
               F.last(
                   F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column),
                   ignorenulls=True,
               )
               for index in where
           ]
   ```
   
   Then
   
   ```python
           # The data is expected to be small so it's fine to transpose/use default index.
           with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
               if len(where) == len(set(where)):
                   psdf: DataFrame = DataFrame(sdf)
                   psdf.columns = pd.Index(where)
                   return first_series(psdf.transpose()).rename(self.name)
               else:
                   # If `where` has duplicate items, leverage the pandas directly
                   # since pandas API on Spark doesn't support the duplicate column name.
                   pdf: pd.DataFrame = sdf.limit(1).toPandas()
                   pdf.columns = pd.Index(where)
                   return first_series(DataFrame(pdf.transpose())).rename(self.name)
   ```
   
   ??




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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1058865169


   done the changes


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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r820885856



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5241,9 +5253,16 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
 
         # The data is expected to be small so it's fine to transpose/use default index.
         with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
-            psdf: DataFrame = DataFrame(sdf)
-            psdf.columns = pd.Index(where)
-            return first_series(psdf.transpose()).rename(self.name)
+            if len(where) == len(set(where)) and not isinstance(index_type, TimestampType):
+                psdf: DataFrame = DataFrame(sdf)
+                psdf.columns = pd.Index(where)
+                return first_series(psdf.transpose()).rename(self.name)
+            else:
+                # If `where` has duplicate items, leverage the pandas directly

Review comment:
       @HyukjinKwon . IMHO , this may not be very uncommon case . Is there a reason to not handle this case and throw exception 
   cc @itholic 




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r819963544



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5241,9 +5253,16 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
 
         # The data is expected to be small so it's fine to transpose/use default index.
         with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
-            psdf: DataFrame = DataFrame(sdf)
-            psdf.columns = pd.Index(where)
-            return first_series(psdf.transpose()).rename(self.name)
+            if len(where) == len(set(where)) and not isinstance(index_type, TimestampType):
+                psdf: DataFrame = DataFrame(sdf)
+                psdf.columns = pd.Index(where)
+                return first_series(psdf.transpose()).rename(self.name)
+            else:
+                # If `where` has duplicate items, leverage the pandas directly

Review comment:
       Yeah, this is because pandas API on Spark doesn't support the duplicated column name.
   
   We use the transform for creating result DataFrame after assigning the column which created by using `where`.
   
   So, I think maybe we can just say like:
   ```python
   # If `where` has duplicate items, leverage the pandas directly
   # since pandas API on Spark doesn't support the duplicated column name.
   ```




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


[GitHub] [spark] ueshin closed pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
ueshin closed pull request #35191:
URL: https://github.com/apache/spark/pull/35191


   


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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1067499459


   Thanks merging to master 


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


[GitHub] [spark] Yikun commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
Yikun commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r784446470



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,62 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+        from pyspark.sql.functions import struct, lit, explode, col, row_number
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                struct(
+                    lit(column_prefix_constant + str(index)).alias("identifier"),
+                    self.spark.column.alias("Koalas"),
+                ),
+            ).alias(column_prefix_constant + str(index))
             for index in where
         ]
+        cond.append(index_scol)
         sdf = self._internal.spark_frame.select(cond)
+        columns = [cols for cols in sdf.columns if cols.startswith("col")]
+        sdf = sdf.withColumn("combined_cols", F.array(columns)).drop(*columns)
+        sdf = (
+            sdf.select(index_scol, explode("combined_cols").alias("values"))
+            .withColumn("identifier", col("values.identifier"))
+            .withColumn("value", col("values.Koalas"))
+            .drop("values")
+            .na.drop(subset="value")

Review comment:
       BTW, there was [a complain in lint CI](https://github.com/pralabhkumar/spark/runs/4801311278?check_suite_focus=true#step:15:23), it should be a bug on type hint of `na.drop`, I submit the fixed on https://github.com/apache/spark/pull/35201.
   
   You could just use `dropna(subset="value")` instead of `.na.drop(subset="value")` to work around, and also I think `dropna` is more reasonable and simple in here.




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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1019683150


   @itholic Addressed the review comments, please review 


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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r799222433



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       Yes @itholic , this is working (since __index_level_0__) is sorted.  However , test case with psser.asof([25, 25]) is failing , ambiguous  of duplicate cols in psdf = ps.DataFrame(sdf) . Therefore , in order to  pass above test case , 
   below is the change. 
   ```python
   
   cond = [
               F.last(
                   F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column),
                   ignorenulls=True,
               ).alias(column_prefix_constant + str(index) + "_" + str(idx))
               for idx, index in enumerate(where)
           ]
   
   ```
   Then 
   ```python
   with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
               psdf = ps.DataFrame(sdf)  # type: DataFrame
               df = pd.DataFrame(psdf.transpose().values, columns=[self.name], index=where)
               return df[df.columns[0]]
   
   ```




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


[GitHub] [spark] ueshin commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
ueshin commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r822165144



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [last_index if x is np.nan else x for x in where]
+        else:
+            modified_where = where
+
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.last(

Review comment:
       How about something like https://github.com/ueshin/apache-spark/commit/1b41024b91c9e8dca5d83c5c2793da85f2ba3946?




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r800269304



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       I think we might want to return the pandas-on-Spark Series rather than pandas Series, and should leverage the pandas DataFrame directly when only the `where` has duplicate item. (and seems like `column_prefix_constant` is not necessary?)
   
   So, how about this ??
   
   ```python
           cond = [
               F.last(
                   F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column),
                   ignorenulls=True,
               )
               for index in where
           ]
   ```
   
   Then
   
   ```python
           # The data is expected to be small so it's fine to transpose/use default index.
           with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
               if len(where) == len(set(where)):
                   psdf: DataFrame = DataFrame(sdf)
                   psdf.columns = pd.Index(where)
                   return first_series(psdf.transpose()).rename(self.name)
               else:
                   # If `where` has duplicate items, leverage the pandas directly
                   # since pandas API on Spark doesn't support the duplicate column name.
                   pdf: pd.DataFrame = sdf.limit(1).toPandas()
                   pdf.columns = pd.Index(where)
                   return first_series(DataFrame(pdf.transpose())).rename(self.name)
   ```
   
   ??




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r818287772



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,10 +5229,22 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            max_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [max_index if x is np.nan else x for x in where]
+        else:
+            modified_where = where
+
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.last(
+                F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column),
+                ignorenulls=True,
+            )
+            for idx, index in enumerate(modified_where)
         ]
+

Review comment:
       Yeah, I think we can consider the large set of data in pandas API on Spark for now.
   
   So it's LGTM except https://github.com/apache/spark/pull/35191#discussion_r818272879 and https://github.com/apache/spark/pull/35191#discussion_r818277484 for now.
   
   Thanks for the comments!




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


[GitHub] [spark] itholic commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1014164956


   Thanks for the rebase, let me take a look closer.


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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1017103938


   @itholic , Please let me know about your review comments. 


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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1027608915


   @itholic Gentle ping


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


[GitHub] [spark] HyukjinKwon commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
HyukjinKwon commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1066239871


   Should be good to go if it looks fine to you, Takuya.


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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1060136925


   @itholic Since all the comments addressed , can u please merge the changes 


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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r799222433



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       Yes @itholic , this is working (since __index_level_0__) is sorted.  However , test case with psser.asof([25, 25]) is failing , ambiguous  of duplicate cols in psdf = ps.DataFrame(sdf) . Therefore , in order to  pass above test case , 
   below is the change. 
   ```python
   
   cond = [
               F.last(
                   F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column),
                   ignorenulls=True,
               ).alias(column_prefix_constant + str(index) + "_" + str(idx))
               for idx, index in enumerate(where)
           ]
   
   ```
   Then 
   ```python
   with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
               psdf = ps.DataFrame(sdf)  # type: DataFrame
               df = pd.DataFrame(psdf.transpose().values, columns=[self.name], index=where)
               return df[df.columns[0]]
   
   ```
   
   Please let me know , if its ok , i'll update the PR




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r798208506



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       Can we make `column_prefix_constant + str(index) + "_" + str(idx)`  as variable and reuse here and there ??

##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       I think we can simply use `F.last` with `ignorenulls=True` instead of `F.max` ??
   (https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.functions.last.html)
   
   e.g.
   ```python
           cond = [
               F.last(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column), ignorenulls=True)
               for index in where
       ]
   ```
   
   It returns the last non-null value from given column.




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


[GitHub] [spark] xinrong-databricks commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
xinrong-databricks commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r819367066



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5241,9 +5253,16 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
 
         # The data is expected to be small so it's fine to transpose/use default index.
         with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
-            psdf: DataFrame = DataFrame(sdf)
-            psdf.columns = pd.Index(where)
-            return first_series(psdf.transpose()).rename(self.name)
+            if len(where) == len(set(where)) and not isinstance(index_type, TimestampType):
+                psdf: DataFrame = DataFrame(sdf)
+                psdf.columns = pd.Index(where)
+                return first_series(psdf.transpose()).rename(self.name)
+            else:
+                # If `where` has duplicate items, leverage the pandas directly

Review comment:
       Shall we also mention why series with `TimestampType` index is leveraged pandas directly?




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


[GitHub] [spark] ueshin commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
ueshin commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r821059683



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [last_index if x is np.nan else x for x in where]
+        else:
+            modified_where = where
+
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.last(

Review comment:
       How about using `F.max_by` with `F.monotonically_increasing_id`?




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r818116440



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,10 +5229,22 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            max_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [max_index if x is np.nan else x for x in where]

Review comment:
       My only remaining concern is that we should trigger the Spark job once here when `where` contains `np.nan`.
   
   @Yikun @HyukjinKwon @ueshin @xinrong-databricks Would you mind taking another look for these lines if you find some time ??
   
   If there is no better way, this patch seems fine to me as is.




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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r824380046



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [last_index if x is np.nan else x for x in where]
+        else:
+            modified_where = where
+
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.last(

Review comment:
       @ueshin  Thx for the suggestion , have done the changes as suggested




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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r804720550



##########
File path: python/pyspark/pandas/tests/test_series.py
##########
@@ -2071,6 +2071,22 @@ def test_asof(self):
         with ps.option_context("compute.eager_check", False):
             self.assert_eq(psser.asof(20), 4.0)
 
+        pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 20]), pser.asof([5, 20]))
+
+        pser = pd.Series([4, np.nan, np.nan, 2], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 100]), pser.asof([5, 100]))
+
+        pser = pd.Series([np.nan, 4, 1, 2], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 35]), pser.asof([5, 35]))
+
+        pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([25, 25]), pser.asof([25, 25]))

Review comment:
       For the timestamp , its throwing exception , since Timestamp name is  like tuple so pd.Index , throws assertion error  assert is_name_like_tuple(column_label, check_type=True), column_label .  However the earlier  code(suggested one)  is working fine  . Currently working on resolving it 




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


[GitHub] [spark] AmplabJenkins commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1012464161


   Can one of the admins verify this patch?


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


[GitHub] [spark] Yikun commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
Yikun commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r784446470



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,62 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+        from pyspark.sql.functions import struct, lit, explode, col, row_number
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                struct(
+                    lit(column_prefix_constant + str(index)).alias("identifier"),
+                    self.spark.column.alias("Koalas"),
+                ),
+            ).alias(column_prefix_constant + str(index))
             for index in where
         ]
+        cond.append(index_scol)
         sdf = self._internal.spark_frame.select(cond)
+        columns = [cols for cols in sdf.columns if cols.startswith("col")]
+        sdf = sdf.withColumn("combined_cols", F.array(columns)).drop(*columns)
+        sdf = (
+            sdf.select(index_scol, explode("combined_cols").alias("values"))
+            .withColumn("identifier", col("values.identifier"))
+            .withColumn("value", col("values.Koalas"))
+            .drop("values")
+            .na.drop(subset="value")

Review comment:
       BTW, there was [a complain in lint CI](https://github.com/pralabhkumar/spark/runs/4801311278?check_suite_focus=true#step:15:23), it should be a bug on type hint of `na.drop`, I submit the error on [1].
   
   You could just use `dropna(subset="value")` instead of `.na.drop(subset="value")` to work around.
   
   [1] https://github.com/apache/spark/pull/35201




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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r784503236



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,62 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+        from pyspark.sql.functions import struct, lit, explode, col, row_number
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                struct(
+                    lit(column_prefix_constant + str(index)).alias("identifier"),
+                    self.spark.column.alias("Koalas"),
+                ),
+            ).alias(column_prefix_constant + str(index))
             for index in where
         ]
+        cond.append(index_scol)
         sdf = self._internal.spark_frame.select(cond)
+        columns = [cols for cols in sdf.columns if cols.startswith("col")]
+        sdf = sdf.withColumn("combined_cols", F.array(columns)).drop(*columns)
+        sdf = (
+            sdf.select(index_scol, explode("combined_cols").alias("values"))
+            .withColumn("identifier", col("values.identifier"))
+            .withColumn("value", col("values.Koalas"))
+            .drop("values")
+            .na.drop(subset="value")

Review comment:
       Thx for the comment , i'll do the same




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


[GitHub] [spark] HyukjinKwon closed pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
HyukjinKwon closed pull request #35191:
URL: https://github.com/apache/spark/pull/35191


   


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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1012097489


   @itholic @HyukjinKwon  Please review . Have added details in jira about the approach. 


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


[GitHub] [spark] itholic commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1022785523


   @pralabhkumar Sorry for being delayed. I've been busy couple of days. Will take a closer look soon 🙏 


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


[GitHub] [spark] HyukjinKwon commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
HyukjinKwon commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1012632076


   @pralabhkumar sorry do you mind rebasing and syncing to the latest master? Seems like something went wrong in CI.


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


[GitHub] [spark] Yikun commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
Yikun commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r784446470



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,62 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+        from pyspark.sql.functions import struct, lit, explode, col, row_number
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                struct(
+                    lit(column_prefix_constant + str(index)).alias("identifier"),
+                    self.spark.column.alias("Koalas"),
+                ),
+            ).alias(column_prefix_constant + str(index))
             for index in where
         ]
+        cond.append(index_scol)
         sdf = self._internal.spark_frame.select(cond)
+        columns = [cols for cols in sdf.columns if cols.startswith("col")]
+        sdf = sdf.withColumn("combined_cols", F.array(columns)).drop(*columns)
+        sdf = (
+            sdf.select(index_scol, explode("combined_cols").alias("values"))
+            .withColumn("identifier", col("values.identifier"))
+            .withColumn("value", col("values.Koalas"))
+            .drop("values")
+            .na.drop(subset="value")

Review comment:
       BTW, there was [a complain in lint CI](https://github.com/pralabhkumar/spark/runs/4801311278?check_suite_focus=true#step:15:23), it should be a bug on type hint of `na.drop`, I submit the fixed on [1].
   
   You could just use `dropna(subset="value")` instead of `.na.drop(subset="value")` to work around.
   
   [1] https://github.com/apache/spark/pull/35201




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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1012759452


   @HyukjinKwon Will rebase and sync to latest master. 


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


[GitHub] [spark] itholic commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1060137716


   @HyukjinKwon @ueshin Seems it's pretty fine to merge for now. Could you take a last look ?


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


[GitHub] [spark] xinrong-databricks commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
xinrong-databricks commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r820327609



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5241,9 +5253,16 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
 
         # The data is expected to be small so it's fine to transpose/use default index.
         with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
-            psdf: DataFrame = DataFrame(sdf)
-            psdf.columns = pd.Index(where)
-            return first_series(psdf.transpose()).rename(self.name)
+            if len(where) == len(set(where)) and not isinstance(index_type, TimestampType):
+                psdf: DataFrame = DataFrame(sdf)
+                psdf.columns = pd.Index(where)
+                return first_series(psdf.transpose()).rename(self.name)
+            else:
+                # If `where` has duplicate items, leverage the pandas directly

Review comment:
       Got it, thanks




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


[GitHub] [spark] pralabhkumar edited a comment on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar edited a comment on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1017182630


   @itholic   Thx for the comments , working on it 


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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r789686756



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,62 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+        from pyspark.sql.functions import struct, lit, explode, col, row_number
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                struct(
+                    lit(column_prefix_constant + str(index)).alias("identifier"),
+                    self.spark.column.alias("Koalas"),

Review comment:
       changed the alias name , it was required to alias the column , so that i can easily refer it later on




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r818287772



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,10 +5229,22 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            max_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [max_index if x is np.nan else x for x in where]
+        else:
+            modified_where = where
+
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.last(
+                F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column),
+                ignorenulls=True,
+            )
+            for idx, index in enumerate(modified_where)
         ]
+

Review comment:
       Yeah, I think we can consider the large set of data in pandas API on Spark for now.
   
   So it's LGTM except https://github.com/apache/spark/pull/35191#discussion_r818272879 and https://github.com/apache/spark/pull/35191#discussion_r818277484.
   
   Thanks for the comments!




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r817259440



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,10 +5229,26 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
-        cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
-        ]
+
+        if np.nan in where:
+            max_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [max_index if x is np.nan else x for x in where]
+            cond = [
+                F.last(
+                    F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column),
+                    ignorenulls=True,
+                )
+                for idx, index in enumerate(modified_where)
+            ]
+        else:
+            cond = [
+                F.last(
+                    F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column),
+                    ignorenulls=True,
+                )
+                for idx, index in enumerate(where)
+            ]

Review comment:
       nit: I think maybe we can unify the `cond` and leave some comment to improve a bit of readability.
   
   e.g.
   ```python
           if np.nan in where:
               # When `where` is np.nan, pandas returns the last index value.
               max_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
               modified_where = [max_index if x is np.nan else x for x in where]
           else:
               modified_where = where
   
           cond = [
               F.last(
                   F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column),
                   ignorenulls=True,
               )
               for idx, index in enumerate(modified_where)
           ]
   ```




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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r820883832



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]

Review comment:
       Will do it . 




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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r800290766



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       @itholic  Yes i think this is good suggestion.  Please let me know , if I update this PR , or you are planning to create new PR with the suggested code changes. 




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


[GitHub] [spark] ueshin commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
ueshin commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1067098669


   Thanks! merging to master.


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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r799222433



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       Yes @itholic , this is working (since __index_level_0__) is sorted.  However , test case with psser.asof([25, 25]) , ambiguous  of duplicate cols in psdf = ps.DataFrame(sdf) . Therefore , in order to  pass above test case , 
   below is the change. 
   ```python
   
   cond = [
               F.last(
                   F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column),
                   ignorenulls=True,
               ).alias(column_prefix_constant + str(index) + "_" + str(idx))
               for idx, index in enumerate(where)
           ]
   
   ```
   Then 
   ```python
   with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
               psdf = ps.DataFrame(sdf)  # type: DataFrame
               df = pd.DataFrame(psdf.transpose().values, columns=[self.name], index=where)
               return df[df.columns[0]]
   
   ```




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


[GitHub] [spark] itholic edited a comment on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic edited a comment on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1028371398


   @pralabhkumar Just came back from vacation. Will leave the comment very soon! 🙏 


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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r798221462



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       I think maybe we can use `F.last` with `ignorenulls=True` instead of `F.max` ??
   (https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.functions.last.html)
   
   e.g.
   ```python
           cond = [
               F.last(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column), ignorenulls=True)
               for index in where
           ]
   ```
   
   It returns the last non-null value from given column, and seems like you want to do this in your fix.
   
   If this works, I think we simply need to fix only this part.




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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r820103719



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5241,9 +5253,16 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
 
         # The data is expected to be small so it's fine to transpose/use default index.
         with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
-            psdf: DataFrame = DataFrame(sdf)
-            psdf.columns = pd.Index(where)
-            return first_series(psdf.transpose()).rename(self.name)
+            if len(where) == len(set(where)) and not isinstance(index_type, TimestampType):
+                psdf: DataFrame = DataFrame(sdf)
+                psdf.columns = pd.Index(where)
+                return first_series(psdf.transpose()).rename(self.name)
+            else:
+                # If `where` has duplicate items, leverage the pandas directly

Review comment:
       ok . Let me add the 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: 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


[GitHub] [spark] Yikun commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
Yikun commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r818277484



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,10 +5229,22 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            max_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [max_index if x is np.nan else x for x in where]
+        else:
+            modified_where = where
+
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.last(
+                F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column),
+                ignorenulls=True,
+            )
+            for idx, index in enumerate(modified_where)
         ]
+

Review comment:
       nits: unrelated new line

##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,10 +5229,22 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            max_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]

Review comment:
       nits:  maybe `last_index`
   
   `max` is a little bit confused in here.

##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,10 +5229,22 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            max_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [max_index if x is np.nan else x for x in where]

Review comment:
       I'm ok with this.
   
   - The job only triggered here when `np.nan in where` corner case, no more influence on normal case.
   - Consider the size of `where` is not huge, the cost of `np.nan in where` is okay in here
   - By this, we can follow the pandas behavior.
   
   If we still think futher and make it best, we might using `self.index.values[-1]` or `self.index.to_numpy()[-1]` according to the size of index (`self.index.size`),  it can speed up in smaller data size. But I'm not sure it's necessary or not.




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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r804720550



##########
File path: python/pyspark/pandas/tests/test_series.py
##########
@@ -2071,6 +2071,22 @@ def test_asof(self):
         with ps.option_context("compute.eager_check", False):
             self.assert_eq(psser.asof(20), 4.0)
 
+        pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 20]), pser.asof([5, 20]))
+
+        pser = pd.Series([4, np.nan, np.nan, 2], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 100]), pser.asof([5, 100]))
+
+        pser = pd.Series([np.nan, 4, 1, 2], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 35]), pser.asof([5, 35]))
+
+        pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([25, 25]), pser.asof([25, 25]))

Review comment:
       @itholic For the timestamp , its throwing exception , since Timestamp name is  like tuple so pd.Index , throws assertion error  assert is_name_like_tuple(column_label, check_type=True), column_label .  However the earlier  code(suggested one)  is working fine  . Currently working on resolving it 




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


[GitHub] [spark] ueshin commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
ueshin commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r821059683



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [last_index if x is np.nan else x for x in where]
+        else:
+            modified_where = where
+
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.last(

Review comment:
       How about using `F.max_by` with `F.monotonically_increasing_id`?
   
   ```py
   F.max_by( ... F.when ..., F.monotonically_increasing_id() )
   ```
   
   `F.monotonically_increasing_id()` should be attached to the Spark DataFrame in advance.




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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r823967986



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [last_index if x is np.nan else x for x in where]
+        else:
+            modified_where = where
+
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.last(

Review comment:
       Hi @ueshin . Thx for the suggestion . However, IMHO F.max_by may not work . 
   
   1) Because it will not ignore nulls and also may not work on multiple columns .  For .e.g we have input DF like below 
   
   +------------------------------------------------------------------+-------------------------------------------------------------------+-----------------+
   |CASE WHEN (__index_level_0__ <= CAST(5 AS BIGINT)) THEN Koalas END|CASE WHEN (__index_level_0__ <= CAST(20 AS BIGINT)) THEN Koalas END|__natural_order__|
   +------------------------------------------------------------------+-------------------------------------------------------------------+-----------------+
   |                                                              null|                                                                2.0|                0|
   |                                                              null|                                                                1.0|       8589934592|
   |                                                              null|                                                               null|      17179869184|
   |                                                              null|                                                               null|      25769803776|
   +------------------------------------------------------------------+-------------------------------------------------------------------+-----------------+
   
   What we need is the last not null value and if the column have all null then the null value . So the expected output is (which is what F.last is providing) . 
   
   
   +------------------------------------------------------------------+-------------------------------------------------------------------+-----------------+
   |CASE WHEN (__index_level_0__ <= CAST(5 AS BIGINT)) THEN Koalas END|CASE WHEN (__index_level_0__ <= CAST(20 AS BIGINT)) THEN Koalas END|__natural_order__|
   +------------------------------------------------------------------+-------------------------------------------------------------------+-----------------+
   |                                                              null|                                                                1.0|       8589934592|
   +------------------------------------------------------------------+-------------------------------------------------------------------+-----------------+
   
   Please let me know if I have misunderstood . In my earlier commits , I was able to achieve the same with F.explode 
   




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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1026065839


   @itholic Please review PR . Thx for your time


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


[GitHub] [spark] itholic commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1014166170


   Could you update the PR description with Before & After example ?? e.g. https://github.com/apache/spark/pull/34931


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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1014180845


   > Could you update the PR description with Before & After example ?? e.g. #34931
   
   Done 
   @itholic 


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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r800269304



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       I think we might want to return the pandas-on-Spark Series rather than pandas Series, and should leverage the pandas DataFrame directly when only the `where` has duplicate item.
   
   So, how about this ??
   
   ```python
           cond = [
               F.last(
                   F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column),
                   ignorenulls=True,
               )
               for index in where
           ]
   ```
   
   Then
   
   ```python
           # The data is expected to be small so it's fine to transpose/use default index.
           with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
               if len(where) == len(set(where)):
                   psdf: DataFrame = DataFrame(sdf)
                   psdf.columns = pd.Index(where)
                   return first_series(psdf.transpose()).rename(self.name)
               else:
                   # If `where` has duplicate items, leverage the pandas directly
                   # since pandas API on Spark doesn't support the duplicate column name.
                   pdf: pd.DataFrame = sdf.limit(1).toPandas()
                   pdf.columns = pd.Index(where)
                   return first_series(DataFrame(pdf.transpose())).rename(self.name)
   ```
   
   ??




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r800339061



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       It's okay to just update here! :-)




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r798221462



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       I think maybe we can use `F.last` with `ignorenulls=True` instead of `F.max` ??
   (https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.functions.last.html)
   
   e.g.
   ```python
           cond = [
               F.last(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column), ignorenulls=True)
               for index in where
           ]
   ```
   
   It returns the last non-null value from given column, and seems like you want to do same thing in your fix.
   
   If this works, I think we simply need to fix only this part.

##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       I think maybe we can use `F.last` with `ignorenulls=True` instead of `F.max` ??
   (https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.functions.last.html)
   
   e.g.
   ```python
           cond = [
               F.last(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column), ignorenulls=True)
               for index in where
           ]
   ```
   
   It returns the last non-null value from given column, and seems like you want to do the same thing in your fix.
   
   If this works, I think we simply need to fix only this part.




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


[GitHub] [spark] itholic removed a comment on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic removed a comment on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1014164956


   Thanks for the rebase, let me take a look closer.


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


[GitHub] [spark] itholic commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1014187924


   Thanks! Let me leave some comments after taking deeper look tomorrow.
   
   Btw, you can make the code example more prettier with `python` keyword as below, just FYI :-)
   
   <img width="473" alt="Screen Shot 2022-01-17 at 3 39 29 PM" src="https://user-images.githubusercontent.com/44108233/149719970-b64ee598-cf7f-48f5-b208-7e0cff6f7c5f.png">
   
   this results to:
   
   ```python
   import pandas as pd
   from pyspark import pandas as ps
   import numpy as np
   pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
   psser = ps.from_pandas(pser)
   psser.asof([5, 25])
   5     NaN
   25    2.0
   Name: Koalas, dtype: float64
   
   pser = pd.Series([4, np.nan, np.nan, 2], index=[10, 20, 30, 40], name="Koalas")
   psser = ps.from_pandas(pser)
   psser.asof([5, 100])
   
   5      NaN
   100    4.0
   ```


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


[GitHub] [spark] ueshin commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
ueshin commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r821054399



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [last_index if x is np.nan else x for x in where]
+        else:
+            modified_where = where
+
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.last(

Review comment:
       According to the comment https://github.com/apache/spark/pull/35191/files#r820354270, `F.last` here could also be indeterministic?




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


[GitHub] [spark] HyukjinKwon commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
HyukjinKwon commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1060151586


   I think it needs a sign-off from @ueshin 


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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1054053028


   @itholic Please review the changes 


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


[GitHub] [spark] ueshin commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
ueshin commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1065370861


   @itholic @Yikun  @HyukjinKwon @xinrong-databricks Could you take another look? Thanks.


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


[GitHub] [spark] itholic commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1067301522


   Thanks for your efforts :-)


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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r811543294



##########
File path: python/pyspark/pandas/tests/test_series.py
##########
@@ -2071,6 +2071,22 @@ def test_asof(self):
         with ps.option_context("compute.eager_check", False):
             self.assert_eq(psser.asof(20), 4.0)
 
+        pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 20]), pser.asof([5, 20]))
+
+        pser = pd.Series([4, np.nan, np.nan, 2], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 100]), pser.asof([5, 100]))
+
+        pser = pd.Series([np.nan, 4, 1, 2], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 35]), pser.asof([5, 35]))
+
+        pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([25, 25]), pser.asof([25, 25]))

Review comment:
       Had to revert to earlier code because of this issue . 




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


[GitHub] [spark] itholic edited a comment on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic edited a comment on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1022785523


   @pralabhkumar Sorry for being delayed. I've been busy for couple of days. Will take a closer look soon 🙏 


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


[GitHub] [spark] itholic commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1028371398


   @pralabhkumar Just came back from vacation. Will leave the comment very soon!


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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r798221462



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       I think maybe we can use `F.last` with `ignorenulls=True` instead of `F.max` ??
   (https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.functions.last.html)
   
   e.g.
   ```python
           cond = [
               F.last(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column), ignorenulls=True)
               for index in where
           ]
   ```
   
   It returns the last non-null value from given column.
   
   If this works, I think we simply need to fix only this part.




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r798221462



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,128 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        # e.g where = [10, 20]
+        # In the comments below , will explain how the dataframe will look after transformations.
+        # e.g pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                F.struct(
+                    F.lit(column_prefix_constant + str(index) + "_" + str(idx)).alias("identifier"),
+                    self.spark.column.alias("col_value"),
+                ),
+            ).alias(column_prefix_constant + str(index) + "_" + str(idx))

Review comment:
       I think maybe we can simply use `F.last` with `ignorenulls=True` instead of `F.max` ??
   (https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.functions.last.html)
   
   e.g.
   ```python
           cond = [
               F.last(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column), ignorenulls=True)
               for index in where
       ]
   ```
   
   It returns the last non-null value from given column.
   
   Could you try ??




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r788362544



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,62 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+        from pyspark.sql.functions import struct, lit, explode, col, row_number

Review comment:
       `pyspark.sql.functions` is already imported as `F`. I think we can just reuse it.

##########
File path: python/pyspark/pandas/tests/test_series.py
##########
@@ -2071,6 +2071,18 @@ def test_asof(self):
         with ps.option_context("compute.eager_check", False):
             self.assert_eq(psser.asof(20), 4.0)
 
+        pser = pd.Series([2, 1, np.nan, 4], index=[10, 20, 30, 40], name="Koalas")
+        psser = ps.from_pandas(pser)
+        self.assert_eq(psser.asof([5, 25]), pser.asof([5, 25]))

Review comment:
       How about `psser.asof([25, 25])` ? It might fail

##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,22 +5228,62 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+        from pyspark.sql.functions import struct, lit, explode, col, row_number
+
+        column_prefix_constant = "col_"
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
+            F.when(
+                index_scol <= SF.lit(index).cast(index_type),
+                struct(
+                    lit(column_prefix_constant + str(index)).alias("identifier"),

Review comment:
       Since `where` can be the same value, the column name here can be duplicated.




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


[GitHub] [spark] ueshin commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
ueshin commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r824009010



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [last_index if x is np.nan else x for x in where]
+        else:
+            modified_where = where
+
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.last(

Review comment:
       Could you try https://github.com/ueshin/apache-spark/commit/1b41024b91c9e8dca5d83c5c2793da85f2ba3946?
   That is a bit different from what I first suggested, though.
   It passes all the tests you added.




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


[GitHub] [spark] pralabhkumar commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1065323472


   @ueshin 
   
   Have done the changes but build is failing because of unrelated issues . 
   
   ([Linters, licenses, dependencies and documentation generation])
   
   Could not import extension nbsphinx (exception: No module named 'ipython_genutils')
   6101
   make: *** [Makefile:35: html] Error 2
   6102
                       ------------------------------------------------
   6103
         Jekyll 4.2.1   Please append `--trace` to the `build` command 
   6104
                        for any additional information or backtrace. 
   


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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r814373285



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5241,9 +5253,14 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
 
         # The data is expected to be small so it's fine to transpose/use default index.
         with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
-            psdf: DataFrame = DataFrame(sdf)
-            psdf.columns = pd.Index(where)
-            return first_series(psdf.transpose()).rename(self.name)
+            psdf = ps.DataFrame(sdf)  # type: DataFrame
+            if len(original_where) > 0:
+                df = pd.DataFrame(
+                    psdf.transpose().values, columns=[self.name], index=original_where
+                )
+            else:
+                df = pd.DataFrame(psdf.transpose().values, columns=[self.name], index=where)
+            return df[df.columns[0]]

Review comment:
       Seems like this returns the pandas DataFrame, but we should return the pandas-on-Spark DataFrame.
   
   I think maybe we can just keep the previous fix and address the Timestamp case separately ??
   
   e.g.
   
   ```python
           with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
               if (len(where) == len(set(where))) and not isinstance(index_type, TimestampType):
                   psdf: DataFrame = DataFrame(sdf)
                   psdf.columns = pd.Index(where)
                   return first_series(psdf.transpose()).rename(self.name)
               else:
                   # If `where` has duplicate items, leverage the pandas directly
                   # since pandas API on Spark doesn't support the duplicate column name.
                   pdf: pd.DataFrame = sdf.limit(1).toPandas()
                   pdf.columns = pd.Index(where)
                   return first_series(DataFrame(pdf.transpose())).rename(self.name)
   ```




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


[GitHub] [spark] HyukjinKwon commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
HyukjinKwon commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r820354270



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]

Review comment:
       Sorry for my late review. `last` expression is indeterministic so it doesn't guarantee the order. We should do this after sorting it actually but it would be too expensive. Since it's less likely that `where` is `na.nan`, can we explicitly throw an exception for now?




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


[GitHub] [spark] HyukjinKwon commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
HyukjinKwon commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r820354681



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5241,9 +5253,16 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
 
         # The data is expected to be small so it's fine to transpose/use default index.
         with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
-            psdf: DataFrame = DataFrame(sdf)
-            psdf.columns = pd.Index(where)
-            return first_series(psdf.transpose()).rename(self.name)
+            if len(where) == len(set(where)) and not isinstance(index_type, TimestampType):
+                psdf: DataFrame = DataFrame(sdf)
+                psdf.columns = pd.Index(where)
+                return first_series(psdf.transpose()).rename(self.name)
+            else:
+                # If `where` has duplicate items, leverage the pandas directly

Review comment:
       Can we throw an exception 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: 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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r819290416



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,10 +5229,22 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            max_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]

Review comment:
       done the changes




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


[GitHub] [spark] itholic commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r819963544



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5241,9 +5253,16 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
 
         # The data is expected to be small so it's fine to transpose/use default index.
         with ps.option_context("compute.default_index_type", "distributed", "compute.max_rows", 1):
-            psdf: DataFrame = DataFrame(sdf)
-            psdf.columns = pd.Index(where)
-            return first_series(psdf.transpose()).rename(self.name)
+            if len(where) == len(set(where)) and not isinstance(index_type, TimestampType):
+                psdf: DataFrame = DataFrame(sdf)
+                psdf.columns = pd.Index(where)
+                return first_series(psdf.transpose()).rename(self.name)
+            else:
+                # If `where` has duplicate items, leverage the pandas directly

Review comment:
       Yeah, this is because pandas API on Spark doesn't support the duplicated column name.
   
   We use the transform for creating result DataFrame after assigning the column which created by using `where`.
   
   So, we can just say like:
   ```python
   # If `where` has duplicate items, leverage the pandas directly
   # since pandas API on Spark doesn't support the duplicated column name.
   ```




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


[GitHub] [spark] itholic commented on pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
itholic commented on pull request #35191:
URL: https://github.com/apache/spark/pull/35191#issuecomment-1057402502


   Thanks! Looks fine to me.


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


[GitHub] [spark] pralabhkumar commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
pralabhkumar commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r820883832



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]

Review comment:
       Agree this may not be very common case and we can throw exception instead of handling it . I can do that. 
   
   cc @itholic 




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


[GitHub] [spark] ueshin commented on a change in pull request #35191: [SPARK-37491][PYTHON]Fix Series.asof for unsorted values

Posted by GitBox <gi...@apache.org>.
ueshin commented on a change in pull request #35191:
URL: https://github.com/apache/spark/pull/35191#discussion_r822010938



##########
File path: python/pyspark/pandas/series.py
##########
@@ -5228,9 +5229,20 @@ def asof(self, where: Union[Any, List]) -> Union[Scalar, "Series"]:
             where = [where]
         index_scol = self._internal.index_spark_columns[0]
         index_type = self._internal.spark_type_for(index_scol)
+
+        if np.nan in where:
+            # When `where` is np.nan, pandas returns the last index value.
+            last_index = self._internal.spark_frame.select(F.last(index_scol)).take(1)[0][0]
+            modified_where = [last_index if x is np.nan else x for x in where]
+        else:
+            modified_where = where
+
         cond = [
-            F.max(F.when(index_scol <= SF.lit(index).cast(index_type), self.spark.column))
-            for index in where
+            F.last(

Review comment:
       The document says `F.last` is non-deterministic.
   
   https://github.com/apache/spark/blob/master/python/pyspark/sql/functions.py#L1337-L1340
   
   Even if the dataframe is sorted beforehand, `F.last` will cause a shuffle because it's an aggregate function, thus the result may be non-deterministic.




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