Path: blob/main/docs/source/src/rust/user-guide/expressions/expression-expansion.rs
7889 views
fn main() -> Result<(), Box<dyn std::error::Error>> {1// --8<-- [start:df]2use polars::prelude::*;34// Data as of 14th October 2024, ~3pm UTC5let df = df!(6"ticker" => ["AAPL", "NVDA", "MSFT", "GOOG", "AMZN"],7"company_name" => ["Apple", "NVIDIA", "Microsoft", "Alphabet (Google)", "Amazon"],8"price" => [229.9, 138.93, 420.56, 166.41, 188.4],9"day_high" => [231.31, 139.6, 424.04, 167.62, 189.83],10"day_low" => [228.6, 136.3, 417.52, 164.78, 188.44],11"year_high" => [237.23, 140.76, 468.35, 193.31, 201.2],12"year_low" => [164.08, 39.23, 324.39, 121.46, 118.35],13)?;1415println!("{df}");16// --8<-- [end:df]1718// --8<-- [start:col-with-names]19let eur_usd_rate = 1.09; // As of 14th October 20242021let result = df22.clone()23.lazy()24.with_column(25(cols(["price", "day_high", "day_low", "year_high", "year_low"]).as_expr()26/ lit(eur_usd_rate))27.round(2, RoundMode::default()),28)29.collect()?;30println!("{result}");31// --8<-- [end:col-with-names]3233// --8<-- [start:expression-list]34let exprs = [35(col("price") / lit(eur_usd_rate)).round(2, RoundMode::default()),36(col("day_high") / lit(eur_usd_rate)).round(2, RoundMode::default()),37(col("day_low") / lit(eur_usd_rate)).round(2, RoundMode::default()),38(col("year_high") / lit(eur_usd_rate)).round(2, RoundMode::default()),39(col("year_low") / lit(eur_usd_rate)).round(2, RoundMode::default()),40];4142let result2 = df.clone().lazy().with_columns(exprs).collect()?;43println!("{}", result.equals(&result2));44// --8<-- [end:expression-list]4546// --8<-- [start:col-with-dtype]47let result = df48.clone()49.lazy()50.with_column(51(dtype_col(&DataType::Float64).as_selector().as_expr() / lit(eur_usd_rate))52.round(2, RoundMode::default()),53)54.collect()?;55println!("{result}");56// --8<-- [end:col-with-dtype]5758// --8<-- [start:col-with-dtypes]59let result2 = df60.clone()61.lazy()62.with_column(63(dtype_cols([DataType::Float32, DataType::Float64])64.as_selector()65.as_expr()66/ lit(eur_usd_rate))67.round(2, RoundMode::default()),68)69.collect()?;70println!("{}", result.equals(&result2));71// --8<-- [end:col-with-dtypes]7273// --8<-- [start:col-with-regex]74// NOTE: Using regex inside `col`/`cols` requires the feature flag `regex`.75let result = df76.clone()77.lazy()78.select([cols(["ticker", "^.*_high$", "^.*_low$"]).as_expr()])79.collect()?;80println!("{result}");81// --8<-- [end:col-with-regex]8283// --8<-- [start:all]84let result = df.clone().lazy().select([all().as_expr()]).collect()?;85println!("{}", result.equals(&df));86// --8<-- [end:all]8788// --8<-- [start:all-exclude]89let result = df90.clone()91.lazy()92.select([all().exclude_cols(["^day_.*$"]).as_expr()])93.collect()?;94println!("{result}");95// --8<-- [end:all-exclude]9697// --8<-- [start:col-exclude]98let result = df99.clone()100.lazy()101.select([dtype_col(&DataType::Float64)102.as_selector()103.exclude_cols(["^day_.*$"])104.as_expr()])105.collect()?;106println!("{result}");107// --8<-- [end:col-exclude]108109// --8<-- [start:duplicate-error]110let gbp_usd_rate = 1.31; // As of 14th October 2024111112let result = df113.clone()114.lazy()115.select([116col("price") / lit(gbp_usd_rate),117col("price") / lit(eur_usd_rate),118])119.collect();120match result {121Ok(df) => println!("{df}"),122Err(e) => println!("{e}"),123};124// --8<-- [end:duplicate-error]125126// --8<-- [start:alias]127let _result = df128.clone()129.lazy()130.select([131(col("price") / lit(gbp_usd_rate)).alias("price (GBP)"),132(col("price") / lit(eur_usd_rate)).alias("price (EUR)"),133])134.collect()?;135// --8<-- [end:alias]136137// --8<-- [start:prefix-suffix]138let result = df139.clone()140.lazy()141.select([142(col("^year_.*$") / lit(eur_usd_rate))143.name()144.prefix("in_eur_"),145(cols(["day_high", "day_low"]).as_expr() / lit(gbp_usd_rate))146.name()147.suffix("_gbp"),148])149.collect()?;150println!("{result}");151// --8<-- [end:prefix-suffix]152153// --8<-- [start:name-map]154// There is also `name().to_uppercase()`, so this usage of `map` is moot.155let result = df156.clone()157.lazy()158.select([all()159.as_expr()160.name()161.map(PlanCallback::new(|name: PlSmallStr| {162Ok(PlSmallStr::from_string(name.to_ascii_uppercase()))163}))])164.collect()?;165println!("{result}");166// --8<-- [end:name-map]167168// --8<-- [start:for-with_columns]169let mut result = df.clone().lazy();170for tp in ["day", "year"] {171let high = format!("{tp}_high");172let low = format!("{tp}_low");173let aliased = format!("{tp}_amplitude");174result = result.with_column((col(high) - col(low)).alias(aliased))175}176let result = result.collect()?;177println!("{result}");178// --8<-- [end:for-with_columns]179180// --8<-- [start:yield-expressions]181let mut exprs: Vec<Expr> = vec![];182for tp in ["day", "year"] {183let high = format!("{tp}_high");184let low = format!("{tp}_low");185let aliased = format!("{tp}_amplitude");186exprs.push((col(high) - col(low)).alias(aliased))187}188let result = df.lazy().with_columns(exprs).collect()?;189println!("{result}");190// --8<-- [end:yield-expressions]191192// --8<-- [start:selectors]193// Selectors are not available in Rust yet.194// Refer to https://github.com/pola-rs/polars/issues/10594195// --8<-- [end:selectors]196197// --8<-- [start:selectors-set-operations]198// Selectors are not available in Rust yet.199// Refer to https://github.com/pola-rs/polars/issues/10594200// --8<-- [end:selectors-set-operations]201202// --8<-- [start:selectors-expressions]203// Selectors are not available in Rust yet.204// Refer to https://github.com/pola-rs/polars/issues/10594205// --8<-- [end:selectors-expressions]206207// --8<-- [start:selector-ambiguity]208// Selectors are not available in Rust yet.209// Refer to https://github.com/pola-rs/polars/issues/10594210// --8<-- [end:selector-ambiguity]211212// --8<-- [start:as_expr]213// Selectors are not available in Rust yet.214// Refer to https://github.com/pola-rs/polars/issues/10594215// --8<-- [end:as_expr]216217// --8<-- [start:is_selector]218// Selectors are not available in Rust yet.219// Refer to https://github.com/pola-rs/polars/issues/10594220// --8<-- [end:is_selector]221222// --8<-- [start:expand_selector]223// Selectors are not available in Rust yet.224// Refer to https://github.com/pola-rs/polars/issues/10594225// --8<-- [end:expand_selector]226227Ok(())228}229230231