Extracting a Rust Polars dataframe value as a scalar value
Asked Answered
A

2

8

I have the following code to find the mean of the ages in the dataframe.

let df = df! [
    "name" => ["panda", "polarbear", "seahorse"],
    "age" => [5, 7, 1],
].unwrap();

let mean = df
    .lazy()
    .select([col("age").mean()])
    .collect().unwrap();

println!("{:?}", mean);

After finding the mean, I want to extract the value as an f64.

┌──────────┐
│ age      │
│ ---      │
│ f64      │   -----> how to transform into a single f64 of value 4.333333?
╞══════════╡
│ 4.333333 │
└──────────┘

Normally, I would do something like df[0,0] to extract the only value. However, as Polars is not a big proponent of indexing, how would one do it using Rust Polars?

Agosto answered 12/11, 2022 at 11:12 Comment(0)
A
5

Ok guys I found a couple of ways to do this. Although, I'm not sure if they are the most efficient.

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>()?;
Agosto answered 12/11, 2022 at 12:12 Comment(0)
D
1
mean["age"].max().unwrap()

or

mean["age"].f64().unwrap().get(0).unwrap()
Disjointed answered 6/2, 2023 at 5:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.