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
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
Share
Improve this question
edited 2 days ago
cafce25
27.5k5 gold badges44 silver badges55 bronze badges
asked Feb 17 at 22:11
OldManSephOldManSeph
2,72118 silver badges22 bronze badges
1 Answer
Reset to default 1You 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);