Search code examples
rustrust-polars

how to extract value from polars series in rust


I can't seem to figure out how to get the value out of a Polars Series in Rust.

I can build a dataframe, sort it, query a column, but then can't figure out how to 'get' te value from that series. The closest i can get is an Int32() object... I'm not sure what that is or how to get the value OUT of it....

let s = Series::new("source", &[0, 98, 50]);
let d: Series = Series::new("destination", &[0, 50, 52]);
let r: Series = Series::new("range", &[-1, 2, 48]);
let df = DataFrame::new(vec![s, d, r]).unwrap();
let sdf = df.sort(["source", "destination", "range"], false, true).unwrap();

let x = 79;
// find row where seed is between source and source+range
let sources = sdf.column("source").unwrap();
// find index of value less than seed
let mask = sources.lt_eq(x).unwrap();
let less_df = sdf.filter(&mask).unwrap();

let sources = less_df.column("source").unwrap();
let destinations = less_df.column("destination").unwrap();
let ranges = less_df.column("range").unwrap();

let num_sources = sources.len();
let src_start = sources.get(num_sources - 1).unwrap();
let dst_start = destinations.get(num_sources - 1).unwrap();
let range = ranges.get(num_sources - 1).unwrap();
println!("{:?} {:?} {:?}", src_start, dst_start, range);
   

Produces:

Int32(50) Int32(52) Int32(48)

But adding a line like

let y = x - src_start;

gives this compiler error/help, which I can't seem to sort out what to DO

error[E0277]: cannot subtract `AnyValue<'_>` from `{integer}`
   --> src/main.rs:165:19
    |
165 |         let y = x - src_start;
    |                   ^ no implementation for `{integer} - AnyValue<'_>`
    |
    = help: the trait `Sub<AnyValue<'_>>` is not implemented for `{integer}`
    = help: the following other types implement trait `Sub<Rhs>`:
              <isize as Sub>
              <isize as Sub<&isize>>
              <i8 as Sub>
              <i8 as Sub<&i8>>
              <i16 as Sub>
              <i16 as Sub<&i16>>
              <i32 as Sub>
              <i32 as Sub<&i32>>
            and 56 others

For more information about this error, try `rustc --explain E0277`.

How do I "extract" the value locked up in the src_start variable?


Solution

  • Series are dynamically typed. You can make them strongly typed ChunkedArrays by using the i32 (or whichever type the series is) accessor:

    let src_start = sources.i32().expect("not i32").get(num_sources - 1).expect("was null");