Path: blob/main/docs/source/src/rust/user-guide/expressions/structs.rs
7889 views
fn main() -> Result<(), Box<dyn std::error::Error>> {1// --8<-- [start:ratings_df]2use polars::prelude::*;3let ratings = df!(4"Movie"=> ["Cars", "IT", "ET", "Cars", "Up", "IT", "Cars", "ET", "Up", "Cars"],5"Theatre"=> ["NE", "ME", "IL", "ND", "NE", "SD", "NE", "IL", "IL", "NE"],6"Avg_Rating"=> [4.5, 4.4, 4.6, 4.3, 4.8, 4.7, 4.5, 4.9, 4.7, 4.6],7"Count"=> [30, 27, 26, 29, 31, 28, 28, 26, 33, 28],89)?;10println!("{}", &ratings);11// --8<-- [end:ratings_df]1213// --8<-- [start:state_value_counts]14let result = ratings15.clone()16.lazy()17.select([col("Theatre").value_counts(true, true, "count", false)])18.collect()?;19println!("{result}");20// --8<-- [end:state_value_counts]2122// --8<-- [start:struct_unnest]23let result = ratings24.clone()25.lazy()26.select([col("Theatre").value_counts(true, true, "count", false)])27.unnest(by_name(["Theatre"], true), None)28.collect()?;29println!("{result}");30// --8<-- [end:struct_unnest]3132// --8<-- [start:series_struct]33// Don't think we can make it the same way in rust, but this works34let rating_series = df!(35"Movie" => &["Cars", "Toy Story"],36"Theatre" => &["NE", "ME"],37"Avg_Rating" => &[4.5, 4.9],38)?39.into_struct("ratings".into())40.into_series();41println!("{}", &rating_series);42// // --8<-- [end:series_struct]4344// --8<-- [start:series_struct_error]45// Contribute the Rust translation of the Python example by opening a PR.46// --8<-- [end:series_struct_error]4748// --8<-- [start:series_struct_extract]49let result = rating_series.struct_()?.field_by_name("Movie")?;50println!("{result}");51// --8<-- [end:series_struct_extract]5253// --8<-- [start:series_struct_rename]54// Contribute the Rust translation of the Python example by opening a PR.55// --8<-- [end:series_struct_rename]5657// --8<-- [start:struct-rename-check]58// Contribute the Rust translation of the Python example by opening a PR.59// --8<-- [end:struct-rename-check]6061// --8<-- [start:struct_duplicates]62// Contribute the Rust translation of the Python example by opening a PR.63// --8<-- [end:struct_duplicates]6465// --8<-- [start:struct_ranking]66let result = ratings67.lazy()68.with_columns([as_struct(vec![col("Count"), col("Avg_Rating")])69.rank(70RankOptions {71method: RankMethod::Dense,72descending: true,73},74None,75)76.over([col("Movie"), col("Theatre")])77.alias("Rank")])78// .filter(as_struct(&[col("Movie"), col("Theatre")]).is_duplicated())79// Error: .is_duplicated() not available if you try that80// https://github.com/pola-rs/polars/issues/380381.filter(len().over([col("Movie"), col("Theatre")]).gt(lit(1)))82.collect()?;83println!("{result}");84// --8<-- [end:struct_ranking]8586// --8<-- [start:multi_column_apply]87let df = df!(88"keys" => ["a", "a", "b"],89"values" => [10, 7, 1],90)?;9192let result = df93.lazy()94.select([95// pack to struct to get access to multiple fields in a custom `apply/map`96as_struct(vec![col("keys"), col("values")])97// we will compute the len(a) + b98.apply(99|s| {100// downcast to struct101let ca = s.struct_()?;102103// get the fields as Series104let s_a = &ca.fields_as_series()[0];105let s_b = &ca.fields_as_series()[1];106107// downcast the `Series` to their known type108let ca_a = s_a.str()?;109let ca_b = s_b.i32()?;110111// iterate both `ChunkedArrays`112let result: Int32Chunked = ca_a113.into_iter()114.zip(ca_b)115.map(|(opt_a, opt_b)| match (opt_a, opt_b) {116(Some(a), Some(b)) => Some(a.len() as i32 + b),117_ => None,118})119.collect();120121Ok(result.into_column())122},123|_, f| Ok(Field::new(f.name().clone(), DataType::Int32)),124)125// note: the `'solution_map_elements'` alias is just there to show how you126// get the same output as in the Python API example.127.alias("solution_map_elements"),128(col("keys").str().count_matches(lit("."), true) + col("values"))129.alias("solution_expr"),130])131.collect()?;132println!("{result}");133// --8<-- [end:multi_column_apply]134135// --8<-- [start:ack]136// Contribute the Rust translation of the Python example by opening a PR.137// --8<-- [end:ack]138139// --8<-- [start:struct-ack]140// Contribute the Rust translation of the Python example by opening a PR.141// --8<-- [end:struct-ack]142143Ok(())144}145146147