Pivot tables in polars

Polars has support for pivot tables under a feature flag, but it seems like the only way to construct them is via polars-ops which is "not intended for external usage." What are the best practices for making pivot tables, or just reshaping data from narrow to wide?

There is an example in the eager cookbook:

Polars' prelude is absolutely wild, I still haven't found out how polars_ops::frame::pivot::pivot makes it in there.

I like to avoid glob imports but should probably just give up in this case!

I do try to avoid it, too, even with polars prelude. Which is kind of weird and defeats the purpose of a prelude module, but a lot of stuff—most of it probably re-exported from libraries that are meant to be workspace-internal, like polars-ops— is only available from the prelude.

I like to avoid glob imports but should probably just give up in this case!

Remember that just because a module is called prelude doesn't mean you have to glob-import it; you can also import it normally or with a rename. If you write

use polars::prelude as p;

then you can copy Polars example code and sprinkle p:: in where needed, without any glob import and without needing to know whether the items are available in non-prelude locations.


(For those wondering why any of this matters, here's a decent article: Don't Use Preludes And Globs | corrode Rust Consulting)

1 Like

Also note that their Rust API is worse documented than the Python API. The examples in both the cookbook link posted above by @jofas and the Rust usage guide show incorrect order of columns for the shown result. The Python docs show the correct order of arguments (well, they're used as keyword args, so order doesn't really matter).