Path: blob/main/docs/source/src/rust/user-guide/transformations/pivot.rs
7889 views
// --8<-- [start:setup]1use polars::prelude::*;2// --8<-- [end:setup]34fn main() -> Result<(), Box<dyn std::error::Error>> {5// --8<-- [start:df]6let df = df!(7"foo"=> ["A", "A", "B", "B", "C"],8"bar"=> ["k", "l", "m", "n", "o"],9"N"=> [1, 2, 2, 4, 2],10)?;11println!("{}", &df);12// --8<-- [end:df]1314// --8<-- [start:eager]15let out = df16.clone()17.lazy()18.pivot(19Selector::ByName {20names: [PlSmallStr::from("foo")].into(),21strict: true,22},23Arc::new(df!("" => ["A", "B", "C"])?),24Selector::ByName {25names: [PlSmallStr::from("bar")].into(),26strict: true,27},28Selector::ByName {29names: [PlSmallStr::from("N")].into(),30strict: true,31},32Expr::Agg(AggExpr::Item {33input: Arc::new(Expr::Element),34allow_empty: true,35}),36false,37"_".into(),38)39.collect()?;40println!("{}", &out);41// --8<-- [end:eager]4243// --8<-- [start:lazy]44let q = df.clone().lazy();45let q2 = q.pivot(46Selector::ByName {47names: [PlSmallStr::from("foo")].into(),48strict: true,49},50Arc::new(df!("" => ["A", "B", "C"])?),51Selector::ByName {52names: [PlSmallStr::from("bar")].into(),53strict: true,54},55Selector::ByName {56names: [PlSmallStr::from("N")].into(),57strict: true,58},59Expr::Agg(AggExpr::Item {60input: Arc::new(Expr::Element),61allow_empty: true,62}),63false,64"_".into(),65);66let out = q2.collect()?;67println!("{}", &out);68// --8<-- [end:lazy]6970Ok(())71}727374