Ben Chuanlong Du's Blog

It is never too late to learn.

Construct Polars DataFrames in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [4]:
:timing
:sccache 1
:dep polars = { version = "0.21.1", features = ["lazy", "parquet"] }
In [26]:
use polars::prelude::*;
use polars::df;

Construct DataFrames

Construct a DataFrame using the df macro.

In [26]:
// use macro
let df = df![
    "names" => ["a", "b", "c"],
    "values" => [1, 2, 3],
    "values_nulls" => [Some(1), None, Some(3)]
].unwrap();
df
Out[26]:
shape: (3, 3)
┌───────┬────────┬──────────────┐
│ names ┆ values ┆ values_nulls │
│ ---   ┆ ---    ┆ ---          │
│ str   ┆ i32    ┆ i32          │
╞═══════╪════════╪══════════════╡
│ a     ┆ 1      ┆ 1            │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ b     ┆ 2      ┆ null         │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ c     ┆ 3      ┆ 3            │
└───────┴────────┴──────────────┘

Construct a polars DataFrame from a vector of Series.

In [4]:
let s1 = Series::new("names", &["a", "b", "c"]);
let s2 = Series::new("values", &[Some(1), None, Some(3)]);
let df = DataFrame::new(vec![s1, s2]).unwrap();
df
Out[4]:
shape: (3, 2)
+-------+--------+
| names | values |
| ---   | ---    |
| str   | i32    |
+=======+========+
| a     | 1      |
+-------+--------+
| b     | null   |
+-------+--------+
| c     | 3      |
+-------+--------+
In [ ]:

Comments