rustrust-polars

Read CSV file into Polars dataframe with Rust


I would like to read the CSV file into a Polars dataframe.

Copying the code from the official documentation fails to run with cargo.

use polars::prelude::*;
use std::fs::File;

fn example() -> Result<DataFrame> {
    let file = File::open("iris.csv").expect("could not open file");

    CsvReader::new(file)
            .infer_schema(None)
            .has_header(true)
            .finish()
}

fn main() {
    let df = example();
    println!("{:?}", df);
}

results in

$ cargo run
   Compiling project v0.1.0
error[E0107]: this enum takes 2 generic arguments but 1 generic argument was supplied
 --> src/main.rs:4:17
  |
4 | fn example() -> Result<DataFrame> {
  |                 ^^^^^^ --------- supplied 1 generic argument
  |                 |
  |                 expected 2 generic arguments
  |
help: add missing generic argument
  |
4 | fn example() -> Result<DataFrame, E> {
  |                                 +++

For more information about this error, try `rustc --explain E0107`.
error: could not compile `eon-playground` due to previous error

Solution

  • You were reading the docs of an old version (you can see that by the "Go to latest version" at the top). In this version, polars::prelude exported an alias of Result. Now it is renamed to PolarsResult, and the updated example is:

    use polars_core::prelude::*;
    use polars_io::prelude::*;
    use std::fs::File;
    
    fn example() -> PolarsResult<DataFrame> {
        CsvReader::from_path("iris_csv")?
                .has_header(true)
                .finish()
    }