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/08/24 17:46:51 UTC

[GitHub] [spark] xinrong-meng commented on a diff in pull request #37635: [WIP][SPARK-40131][PYTHON] Support NumPy ndarray in built-in functions

xinrong-meng commented on code in PR #37635:
URL: https://github.com/apache/spark/pull/37635#discussion_r954103989


##########
python/pyspark/sql/types.py:
##########
@@ -2256,11 +2260,47 @@ def convert(self, obj: datetime.timedelta, gateway_client: GatewayClient) -> Jav
         )
 
 
+class NumpyScalarConverter:
+    def can_convert(self, obj: Any) -> bool:
+        return has_numpy and isinstance(obj, np.generic)
+
+    def convert(self, obj: "np.generic", gateway_client: GatewayClient) -> Any:
+        return obj.item()
+
+
+class NumpyArrayConverter:
+    def can_convert(self, obj: Any) -> bool:
+        return has_numpy and isinstance(obj, np.ndarray)
+
+    def convert(self, obj: "np.ndarray", gateway_client: GatewayClient) -> JavaObject:
+        from pyspark import SparkContext
+
+        gateway = SparkContext._gateway
+        assert gateway is not None
+
+        plist = obj.tolist()
+        ptpe = type(plist[0]) if len(plist) > 0 else float
+        tpe_dict = {
+            int: gateway.jvm.int,
+            float: gateway.jvm.double,
+            bool: gateway.jvm.boolean,
+            str: gateway.jvm.String,
+        }
+        jarr = gateway.new_array(tpe_dict[ptpe], len(plist))
+        for i in range(len(plist)):
+            jarr[i] = plist[i]
+        return jarr
+
+
 # datetime is a subclass of date, we should register DatetimeConverter first
 register_input_converter(DatetimeNTZConverter())
 register_input_converter(DatetimeConverter())
 register_input_converter(DateConverter())
 register_input_converter(DayTimeIntervalTypeConverter())
+register_input_converter(NumpyScalarConverter())
+# NumPy array satisfies py4j.java_collections.ListConverter,
+# so prepend NumpyArrayConverter
+register_input_converter(NumpyArrayConverter(), prepend=True)

Review Comment:
   ```py
   >>> from py4j.java_collections import ListConverter
   >>> ndarr = np.array([1, 2])
   >>> ListConverter().can_convert(ndarr)
   True
   ```



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