timsaucer commented on code in PR #1568:
URL:
https://github.com/apache/datafusion-python/pull/1568#discussion_r3415609040
##########
crates/core/src/functions.rs:
##########
@@ -607,7 +607,19 @@ expr_fn_vec!(named_struct);
expr_fn!(from_unixtime, unixtime);
expr_fn!(arrow_typeof, arg_1);
expr_fn!(arrow_cast, arg_1 datatype);
+expr_fn!(arrow_try_cast, arg_1 datatype);
+expr_fn!(arrow_field, arg_1);
+#[pyfunction]
+#[pyo3(signature = (arg_1, reference, *, try_cast = false))]
+fn cast_to_type(arg_1: PyExpr, reference: PyExpr, try_cast: bool) -> PyExpr {
+ if try_cast {
+ functions::expr_fn::try_cast_to_type(arg_1.into(),
reference.into()).into()
+ } else {
+ functions::expr_fn::cast_to_type(arg_1.into(), reference.into()).into()
+ }
+}
Review Comment:
Good call. Split into separate `cast_to_type` and `try_cast_to_type`
functions in a8d3a5ee, matching upstream and the `arrow_cast` /
`arrow_try_cast` pair.
##########
python/tests/test_functions.py:
##########
@@ -1299,30 +1299,93 @@ def test_make_time(df):
assert result.column(0)[0].as_py() == time(12, 30)
-def test_arrow_cast(df):
- df = df.select(
- f.arrow_cast(column("b"), "Float64").alias("b_as_float"),
- f.arrow_cast(column("b"), "Int32").alias("b_as_int"),
[email protected]("cast_fn", [f.arrow_cast, f.arrow_try_cast])
[email protected](
+ ("data_type", "expected"),
+ [
+ ("Float64", pa.array([4.0, 5.0, 6.0], type=pa.float64())),
+ ("Int32", pa.array([4, 5, 6], type=pa.int32())),
+ (pa.float64(), pa.array([4.0, 5.0, 6.0], type=pa.float64())),
+ (pa.int32(), pa.array([4, 5, 6], type=pa.int32())),
+ (pa.string(), pa.array(["4", "5", "6"], type=pa.string())),
+ ],
+)
+def test_arrow_cast_variants(df, cast_fn, data_type, expected):
+ """arrow_cast / arrow_try_cast accept str and pyarrow target types."""
+ result = df.select(cast_fn(column("b"), data_type).alias("c")).collect()[0]
+ assert result.column(0) == expected
+
+
[email protected]("data_type", ["Float64", pa.float64()])
+def test_arrow_try_cast_null_on_failure(data_type):
+ ctx = SessionContext()
+ batch = pa.RecordBatch.from_arrays([pa.array(["1.5", "oops", "3"])],
names=["s"])
+ df = ctx.create_dataframe([[batch]])
+
+ result = df.select(f.arrow_try_cast(column("s"),
data_type).alias("c")).collect()[0]
+
+ assert result.column(0).to_pylist() == [1.5, None, 3.0]
Review Comment:
Agreed, the `data_type` parametrization was redundant here since the assert
does not depend on it and the str-vs-pyarrow distinction is already covered by
`test_arrow_cast_variants`. Dropped it in a8d3a5ee.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]