With Polars version = "0.30", use:
.with_columns([
cols( col1, col2, ..., colN)
.apply(|series|
some_function(),
GetOutput::from_type(DataType::Float64)
)
]);
The Cargo.toml:
[dependencies]
polars = { version = "0.30", features = [
"lazy", # Lazy API
"round_series", # round underlying float types of Series
] }
And the main() function:
use std::error::Error;
use polars::{
prelude::*,
datatypes::DataType,
};
fn main()-> Result<(), Box<dyn Error>> {
let dataframe01: DataFrame = df!(
"column integers" => &[1, 2, 3, 4, 5, 6],
"column float64 A" => [23.654, 0.319, 10.0049, 89.01999, -3.41501, 52.0766],
"column options" => [Some(28), Some(300), None, Some(2), Some(-30), None],
"column float64 B" => [23.6499, 0.399, 10.0061, 89.0105, -3.4331, 52.099999],
)?;
println!("dataframe01: {dataframe01}
");
let columns_with_float64: Vec<&str> = vec![
"column float64 A",
"column float64 B",
];
// Format only the columns with float64
let lazyframe: LazyFrame = dataframe01
.lazy()
.with_columns([
cols(columns_with_float64)
.apply(|series|
Ok(Some(series.round(2)?)),
GetOutput::from_type(DataType::Float64)
)
]);
let dataframe02: DataFrame = lazyframe.collect()?;
println!("dataframe02: {dataframe02}
");
let series_a: Series = Series::new("column float64 A", &[23.65, 0.32, 10.00, 89.02, -3.42, 52.08]);
let series_b: Series = Series::new("column float64 B", &[23.65, 0.4, 10.01, 89.01, -3.43, 52.1]);
assert_eq!(dataframe02.column("column float64 A")?, &series_a);
assert_eq!(dataframe02.column("column float64 B")?, &series_b);
Ok(())
}
The output:
dataframe01: shape: (6, 4)
┌─────────────────┬──────────────────┬────────────────┬──────────────────┐
│ column integers ┆ column float64 A ┆ column options ┆ column float64 B │
│ --- ┆ --- ┆ --- ┆ --- │
│ i32 ┆ f64 ┆ i32 ┆ f64 │
╞═════════════════╪══════════════════╪════════════════╪══════════════════╡
│ 1 ┆ 23.654 ┆ 28 ┆ 23.6499 │
│ 2 ┆ 0.319 ┆ 300 ┆ 0.399 │
│ 3 ┆ 10.0049 ┆ null ┆ 10.0061 │
│ 4 ┆ 89.01999 ┆ 2 ┆ 89.0105 │
│ 5 ┆ -3.41501 ┆ -30 ┆ -3.4331 │
│ 6 ┆ 52.0766 ┆ null ┆ 52.099999 │
└─────────────────┴──────────────────┴────────────────┴──────────────────┘
dataframe02: shape: (6, 4)
┌─────────────────┬──────────────────┬────────────────┬──────────────────┐
│ column integers ┆ column float64 A ┆ column options ┆ column float64 B │
│ --- ┆ --- ┆ --- ┆ --- │
│ i32 ┆ f64 ┆ i32 ┆ f64 │
╞═════════════════╪══════════════════╪════════════════╪══════════════════╡
│ 1 ┆ 23.65 ┆ 28 ┆ 23.65 │
│ 2 ┆ 0.32 ┆ 300 ┆ 0.4 │
│ 3 ┆ 10.0 ┆ null ┆ 10.01 │
│ 4 ┆ 89.02 ┆ 2 ┆ 89.01 │
│ 5 ┆ -3.42 ┆ -30 ┆ -3.43 │
│ 6 ┆ 52.08 ┆ null ┆ 52.1 │
└─────────────────┴──────────────────┴────────────────┴──────────────────┘