Skip to content

Reshape this Expr to a flat column or an Array column

Source code

Description

Reshape this Expr to a flat column or an Array column

Usage

<Expr>$reshape(dimensions)

Arguments

dimensions A integer vector of length of the dimension size. If -1 is used as the value for the first dimension, that dimension is inferred. Because the size of the Column may not be known in advance, it is only possible to use -1 for the first dimension.

Details

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 Array with shape dimensions.

Value

A polars expression

Examples

library("polars")

df <- pl$DataFrame(foo = 1:8)

df$select(pl$col("foo")$reshape(8))
#> shape: (8, 1)
#> ┌─────┐
#> │ foo │
#> │ --- │
#> │ i32 │
#> ╞═════╡
#> │ 1   │
#> │ 2   │
#> │ 3   │
#> │ 4   │
#> │ 5   │
#> │ 6   │
#> │ 7   │
#> │ 8   │
#> └─────┘
df$select(pl$col("foo")$reshape(c(2, 4)))
#> shape: (2, 1)
#> ┌───────────────┐
#> │ foo           │
#> │ ---           │
#> │ array[i32, 4] │
#> ╞═══════════════╡
#> │ [1, 2, … 4]   │
#> │ [5, 6, … 8]   │
#> └───────────────┘
# Using `-1` for the first dimension to infer the other dimension
df$select(pl$col("foo")$reshape(c(-1, 4)))
#> shape: (2, 1)
#> ┌───────────────┐
#> │ foo           │
#> │ ---           │
#> │ array[i32, 4] │
#> ╞═══════════════╡
#> │ [1, 2, … 4]   │
#> │ [5, 6, … 8]   │
#> └───────────────┘
df$select(pl$col("foo")$reshape(c(-1, 2)))
#> shape: (4, 1)
#> ┌───────────────┐
#> │ foo           │
#> │ ---           │
#> │ array[i32, 2] │
#> ╞═══════════════╡
#> │ [1, 2]        │
#> │ [3, 4]        │
#> │ [5, 6]        │
#> │ [7, 8]        │
#> └───────────────┘
# We can have more than 2 dimensions
df$select(pl$col("foo")$reshape(c(2, 2, 2)))
#> shape: (2, 1)
#> ┌────────────────────┐
#> │ foo                │
#> │ ---                │
#> │ array[i32, (2, 2)] │
#> ╞════════════════════╡
#> │ [[1, 2], [3, 4]]   │
#> │ [[5, 6], [7, 8]]   │
#> └────────────────────┘
df$select(pl$col("foo")$reshape(c(-1, 2, 2)))
#> shape: (2, 1)
#> ┌────────────────────┐
#> │ foo                │
#> │ ---                │
#> │ array[i32, (2, 2)] │
#> ╞════════════════════╡
#> │ [[1, 2], [3, 4]]   │
#> │ [[5, 6], [7, 8]]   │
#> └────────────────────┘