Skip to content

Reshape this Expr to a flat Series or a Series of Lists

Source code

Description

Reshape this Expr to a flat Series or a Series of Lists

Usage

<Expr>$reshape(dimensions, nested_type = pl\$List())

Arguments

dimensions A integer vector of length of the dimension size. If -1 is used in any of the dimensions, that dimension is inferred. Currently, more than two dimensions not supported.
nested_type The nested data type to create. List only supports 2 dimensions, whereas Array supports an arbitrary number of dimensions.

Value

Expr. If a single dimension is given, results in an expression of the original data type. If a multiple dimensions are given, results in an expression of data type List with shape equal to the dimensions.

Examples

library("polars")

df = pl$DataFrame(foo = 1:9)

df$select(pl$col("foo")$reshape(9))
#> shape: (9, 1)
#> ┌─────┐
#> │ foo │
#> │ --- │
#> │ i32 │
#> ╞═════╡
#> │ 1   │
#> │ 2   │
#> │ 3   │
#> │ 4   │
#> │ 5   │
#> │ 6   │
#> │ 7   │
#> │ 8   │
#> │ 9   │
#> └─────┘
df$select(pl$col("foo")$reshape(c(3, 3)))
#> shape: (3, 1)
#> ┌───────────┐
#> │ foo       │
#> │ ---       │
#> │ list[i32] │
#> ╞═══════════╡
#> │ [1, 2, 3] │
#> │ [4, 5, 6] │
#> │ [7, 8, 9] │
#> └───────────┘
# Use `-1` to infer the other dimension
df$select(pl$col("foo")$reshape(c(-1, 3)))
#> shape: (3, 1)
#> ┌───────────┐
#> │ foo       │
#> │ ---       │
#> │ list[i32] │
#> ╞═══════════╡
#> │ [1, 2, 3] │
#> │ [4, 5, 6] │
#> │ [7, 8, 9] │
#> └───────────┘
df$select(pl$col("foo")$reshape(c(3, -1)))
#> shape: (3, 1)
#> ┌───────────┐
#> │ foo       │
#> │ ---       │
#> │ list[i32] │
#> ╞═══════════╡
#> │ [1, 2, 3] │
#> │ [4, 5, 6] │
#> │ [7, 8, 9] │
#> └───────────┘
# One can specify more than 2 dimensions by using the Array type
df = pl$DataFrame(foo = 1:12)
df$select(
  pl$col("foo")$reshape(c(3, 2, 2), nested_type = pl$Array(pl$Float32, 2))
)
#> shape: (3, 1)
#> ┌─────────────────────┐
#> │ foo                 │
#> │ ---                 │
#> │ array[i32, (2, 2)]  │
#> ╞═════════════════════╡
#> │ [[1, 2], [3, 4]]    │
#> │ [[5, 6], [7, 8]]    │
#> │ [[9, 10], [11, 12]] │
#> └─────────────────────┘