ray.data.expressions.UnaryExpr.cast#

UnaryExpr.cast(target_type: DataType, *, safe: bool = True) UDFExpr#

Cast the expression to a specified type.

This method allows you to convert the expression result to a different data type using PyArrow’s cast function. By default, it uses safe casting which raises errors on overflow or invalid conversions.

Parameters:
  • target_type – The Ray Data DataType to cast to, for example DataType.int64(), DataType.float64(), or DataType.string().

  • safe – If True (default), raise errors on overflow or invalid conversions. If False, allow unsafe conversions (which may result in data loss).

Returns:

A UDFExpr that casts the expression to the target type.

Example

>>> from ray.data.expressions import col
>>> from ray.data.datatype import DataType
>>> import ray
>>>
>>> ds = ray.data.range(10)
>>> # Cast float result to int64
>>> ds = ds.with_column("part", (col("id") % 2).cast(DataType.int64()))
>>> # Cast to float64
>>> ds = ds.with_column("id_float", col("id").cast(DataType.float64()))
>>> # Cast to string
>>> ds = ds.with_column("id_str", col("id").cast(DataType.string()))