0

In R, I am stacking a data.frame like so: stack(preds[1:(ncol(preds)-4)])

This selects 1,000 columns, and stacks them all into a single column, while creating a second column which is a string, the name of the column that row originally came from.

I then combine the remaining columns I did not stack with cbind(), which are implicitly repeated since they do not have the same length as the stacked data.frame.

cbind(preds[ncol(preds)], preds[ncol(preds)-3], preds[ncol(preds)-2], preds[ncol(preds)-1], stack(preds[1:(ncol(preds)-4)]))

I am trying to replicate this in Rust using Polars, but cannot find any kind of stacking function. Do I just need to iterate over all the Series to be stacked, calling append(), and manually repeat the remaining columns and join those to the stacked one with with_columns()?

Jage
  • 453
  • 2
  • 9
  • 1
    Sounds to me like the whole pivot / unpivot / melt complex of functionality so I'd explore the docs along those lines. – cadolphs Feb 16 '23 at 02:30
  • 1
    https://docs.rs/polars/latest/polars/frame/struct.DataFrame.html#example-1 – cadolphs Feb 16 '23 at 02:51
  • @cadolphs Thank you, I was not familiar with this terminology, but it looks like what I want. – Jage Feb 16 '23 at 04:20

1 Answers1

0

melt() is the built-in function for this purpose. Note that the current latest release, 0.27.2, is O(n^2). If you need it to be fast you will need to install from the master branch polars = { git = "https://github.com/pola-rs/polars" } to get the latest bug fix that makes it O(n).

Jage
  • 453
  • 2
  • 9