How to get all group in polars by rust? - Stack Overflow

In python, just like thisdf = pl.DataFrame({"foo": ["a", "a", "b&qu

In python, just like this

df = pl.DataFrame({"foo": ["a", "a", "b"], "bar": [1, 2, 3]})
for name, data in df.group_by("foo"):  
    print(name)
    print(data)

output:

(a,)
shape: (2, 2)
┌─────┬─────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ a   ┆ 1   │
│ a   ┆ 2   │
└─────┴─────┘
(b,)
shape: (1, 2)
┌─────┬─────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ b   ┆ 3   │
└─────┴─────┘

How to do same in rust?

In python, just like this

df = pl.DataFrame({"foo": ["a", "a", "b"], "bar": [1, 2, 3]})
for name, data in df.group_by("foo"):  
    print(name)
    print(data)

output:

(a,)
shape: (2, 2)
┌─────┬─────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ a   ┆ 1   │
│ a   ┆ 2   │
└─────┴─────┘
(b,)
shape: (1, 2)
┌─────┬─────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ b   ┆ 3   │
└─────┴─────┘

How to do same in rust?

Share Improve this question edited Mar 30 at 8:50 jqurious 22k5 gold badges20 silver badges39 bronze badges asked Mar 30 at 8:47 NyssanceNyssance 4115 silver badges9 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 4

This works a bit different in Rust, because a lazy DataFrame / LazyGroupBy is used here.
You can do something like this using the apply function:

use polars::prelude::*;

fn main() -> PolarsResult<()> {
    let df = df!(
        "foo" => &["a", "a", "b"],
        "bar" => &[1, 2, 3]
    )?;

    let groups = df.group_by(["foo"])?;
    groups.apply(|group| {
        let group_name =
            group.column("foo")?.str()?.get(0).ok_or_else(|| {
                PolarsError::ComputeError("Failed to retrieve group name.".into())
            })?;
        println!("{}", group_name);
        println!("{:?}", group);
        Ok(group)
    })?;

    Ok(())
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743993004a4540138.html

相关推荐

  • How to get all group in polars by rust? - Stack Overflow

    In python, just like thisdf = pl.DataFrame({"foo": ["a", "a", "b&qu

    10天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信