xos*_*xos 8 rust data-science rust-polars
我有以下代码来查找数据框中年龄的平均值。
\nlet df = df! [\n "name" => ["panda", "polarbear", "seahorse"],\n "age" => [5, 7, 1],\n].unwrap();\n\nlet mean = df\n .lazy()\n .select([col("age").mean()])\n .collect().unwrap();\n\nprintln!("{:?}", mean);\nRun Code Online (Sandbox Code Playgroud)\n找到平均值后,我想将值提取为f64.
\xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x90\n\xe2\x94\x82 age \xe2\x94\x82\n\xe2\x94\x82 --- \xe2\x94\x82\n\xe2\x94\x82 f64 \xe2\x94\x82 -----> how to transform into a single f64 of value 4.333333?\n\xe2\x95\x9e\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xa1\n\xe2\x94\x82 4.333333 \xe2\x94\x82\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x98\nRun Code Online (Sandbox Code Playgroud)\n通常,我会做类似df[0,0]提取唯一值的事情。然而,由于 Polars 并不是索引的大力支持者,那么如何使用 Rust Polars 来做到这一点呢?
好的,我找到了几种方法来做到这一点。虽然,我不确定它们是否是最有效的。
let df = df! [
"name" => ["panda", "polarbear", "seahorse"],
"age" => [5, 7, 1],
]?;
let mean = df
.lazy()
.select([col("age").mean()])
.collect()?;
// Select the column as Series, turn into an iterator, select the first
// item and cast it into an f64
let mean1 = mean.column("age")?.iter().nth(0)?.try_extract::<f64>()?;
// Select the column as Series and calculate the sum as f64
let mean2 = mean.column("age")?.sum::<f64>()?;
Run Code Online (Sandbox Code Playgroud)