rustrust-polars

using format!() with data from polars cells


I am trying to figure out how to get format!() to work when pulling data from a polars dataframe but am not getting the formatting/alignment. It works when passing a String into format!() instead of an AnyValue. I am just now learning polars so I figure there is a step I am missing but am having trouble searching for it.

use chrono::prelude::*;
use polars::prelude::*;

fn main() {
    let mut df: DataFrame = df!(
        "name" => ["Alice Archer", "Ben Brown", "Chloe Cooper", "Daniel Donovan"],
        "birthdate" => [
            NaiveDate::from_ymd_opt(1997, 1, 10).unwrap(),
            NaiveDate::from_ymd_opt(1985, 2, 15).unwrap(),
            NaiveDate::from_ymd_opt(1983, 3, 22).unwrap(),
            NaiveDate::from_ymd_opt(1981, 4, 30).unwrap(),
        ],
        "weight" => [57.9, 72.5, 53.6, 83.1],  // (kg)
        "height" => [1.56, 1.77, 1.65, 1.75],  // (m)
    )
    .unwrap();

    let line_new = format!(
        "{:<10}{:>5}",
        df.column("name").unwrap().get(1).unwrap(),
        df.column("weight").unwrap().get(1).unwrap()
    );
    println!("{}", line_new);
}

Actual Output

"Ben"72

Desired Output

"Ben"         72

Solution

  • You have to extract the values from AnyValue first. To extract the string you can use str_value or(get_str) method. To extract the numerical value you can use try_extract.

    let name = df.column("name").unwrap().get(1).unwrap();
    let weight = df.column("weight").unwrap().get(1).unwrap();
    
    let line_new = format!(
        "{:<10}{:>5}",
        name.str_value(),
        weight.try_extract::<i32>().unwrap()
    );
    println!("{}", line_new);