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. Any help would be greatly appreciated.

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

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

Broadly speaking, the padding options in formatting only work with types that support them or delegate to another type that does.

If you go to the documentation for AnyValue and from there to the source for impl Display for AnyValue, you can see it is implemented as:

AnyValue::String(v) => write!(f, "{}", format_args!("\"{v}\"")),
AnyValue::StringOwned(v) => write!(f, "{}", format_args!("\"{v}\"")),

which is using a format string of its own (I'm not sure why there is both write! and format_args!; that seems redundant) and therefore will ignore padding options.

I’d say that this is a reasonable thing to file a feature request about — or a PR.

1 Like

I’ll look at it more and see if a can come up with something useful to put into a PR. I figured using an AnyValue is what it is. Thank you.

This has been cross-posted to SO: rust - using format!() with data from polars cells - Stack Overflow