Skip to content

Cast LazyFrame column(s) to the specified dtype

Source code

Description

This allows to convert all columns to a datatype or to convert only specific columns. Contrarily to the Python implementation, it is not possible to convert all columns of a specific datatype to another datatype.

Usage

<LazyFrame>$cast(dtypes, ..., strict = TRUE)

Arguments

dtypes Either a datatype or a list where the names are column names and the values are the datatypes to convert to.
Ignored.
strict If TRUE (default), throw an error if a cast could not be done (for instance, due to an overflow). Otherwise, return null.

Value

A LazyFrame

Examples

library("polars")

lf = pl$LazyFrame(
  foo = 1:3,
  bar = c(6, 7, 8),
  ham = as.Date(c("2020-01-02", "2020-03-04", "2020-05-06"))
)

# Cast only some columns
lf$cast(list(foo = pl$Float32, bar = pl$UInt8))$collect()
#> shape: (3, 3)
#> ┌─────┬─────┬────────────┐
#> │ foo ┆ bar ┆ ham        │
#> │ --- ┆ --- ┆ ---        │
#> │ f32 ┆ u8  ┆ date       │
#> ╞═════╪═════╪════════════╡
#> │ 1.0 ┆ 6   ┆ 2020-01-02 │
#> │ 2.0 ┆ 7   ┆ 2020-03-04 │
#> │ 3.0 ┆ 8   ┆ 2020-05-06 │
#> └─────┴─────┴────────────┘
# Cast all columns to the same type
lf$cast(pl$String)$collect()
#> shape: (3, 3)
#> ┌─────┬─────┬────────────┐
#> │ foo ┆ bar ┆ ham        │
#> │ --- ┆ --- ┆ ---        │
#> │ str ┆ str ┆ str        │
#> ╞═════╪═════╪════════════╡
#> │ 1   ┆ 6.0 ┆ 2020-01-02 │
#> │ 2   ┆ 7.0 ┆ 2020-03-04 │
#> │ 3   ┆ 8.0 ┆ 2020-05-06 │
#> └─────┴─────┴────────────┘