admin管理员组

文章数量:1431994

In Rust Polars I have a dataframe with columns a and b and a struct MyStruct with fields a and b (with type u64). I want to convert each row of the dataframe into a MyStruct, returning a vector of MyStructs.

In Polars version 0.41.0 the following works:

let foo = df
  .into_struct("bar")
  .iter()
  .map(|row| MyStruct { 
    row[0].try_extract<u64>().unwrap(),
    row[1].try_extract<u64>().unwrap()
  })
  .collect::<Vec<MyStruct>>();

It is also possible to do this by zipping columns together, but I actually have many fields and find this more concise.

In Cargo.toml the Polars dependency is specified as

polars = { version = "0.41.0" , default-features = false, features = ["dtype-struct", "lazy"] }

Now I want to upgrade to the latest version (0.44.2) and I get compilation errors:

error[E0608]: cannot index into a value of type `Option<()>

referring to the row in map. (Also, the argument to into_struct is now PlSmallStr::from_str("bar"))

I have been looking through the release notes since 0.41.0, but I have found no breaking changes mentioning map/iter.

In Rust Polars I have a dataframe with columns a and b and a struct MyStruct with fields a and b (with type u64). I want to convert each row of the dataframe into a MyStruct, returning a vector of MyStructs.

In Polars version 0.41.0 the following works:

let foo = df
  .into_struct("bar")
  .iter()
  .map(|row| MyStruct { 
    row[0].try_extract<u64>().unwrap(),
    row[1].try_extract<u64>().unwrap()
  })
  .collect::<Vec<MyStruct>>();

It is also possible to do this by zipping columns together, but I actually have many fields and find this more concise.

In Cargo.toml the Polars dependency is specified as

polars = { version = "0.41.0" , default-features = false, features = ["dtype-struct", "lazy"] }

Now I want to upgrade to the latest version (0.44.2) and I get compilation errors:

error[E0608]: cannot index into a value of type `Option<()>

referring to the row in map. (Also, the argument to into_struct is now PlSmallStr::from_str("bar"))

I have been looking through the release notes since 0.41.0, but I have found no breaking changes mentioning map/iter.

Share Improve this question asked Nov 19, 2024 at 7:47 robertdjrobertdj 1,1271 gold badge7 silver badges14 bronze badges 1
  • 1 You could also check the edit of this answer – user459872 Commented Nov 19, 2024 at 12:32
Add a comment  | 

1 Answer 1

Reset to default 2

See also this answer. One way to do it is to create an iterator for each column you're interested in, and iterating them in lockstep:

let mut columns = df
    .columns (["a", "b"])?
    .iter()
    .map (|s| s.iter()).collect::<Vec<_>>();
let foo = (0..df.height())
    .map (|_| MyStruct { 
        columns[0].next().unwrap().try_extract<u64>().unwrap(),
        columns[1].next().unwrap().try_extract<u64>().unwrap(),
    })
    .collect::<Vec<_>>();

本文标签: rustMap over struct in PolarsStack Overflow