Rust Porars:是否可以将列表列爆炸到多个列中?

发布于 2025-02-04 03:08:44 字数 1545 浏览 4 评论 0原文

我的函数可以返回列表类型列。因此,我的专栏之一是列表。我想将此列表列转换为多列。例如:

use polars::prelude::*;
use polars::df;

fn main() {
    let s0 = Series::new("a", &[1i64, 2, 3]);
    let s1 = Series::new("b", &[1i64, 1, 1]);
    let s2 = Series::new("c", &[Some(2i64), None, None]);
    // construct a new ListChunked for a slice of Series.
    let list = Series::new("foo", &[s0, s1, s2]);

    // construct a few more Series.
    let s0 = Series::new("Group", ["A", "B", "A"]);
    let s1 = Series::new("Cost", [1, 1, 1]);
    let df = DataFrame::new(vec![s0, s1, list]).unwrap();

    dbg!(df);

在此阶段,DF看起来像这样:

┌───────┬──────┬─────────────────┐
│ Group ┆ Cost ┆ foo             │
│ ---   ┆ ---  ┆ ---             │
│ str   ┆ i32  ┆ list [i64]      │
╞═══════╪══════╪═════════════════╡
│ A     ┆ 1    ┆ [1, 2, 3]       │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ B     ┆ 1    ┆ [1, 1, 1]       │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ A     ┆ 1    ┆ [2, null, null] │

问题从这里开始,我想得到:

┌───────┬──────┬─────┬──────┬──────┐
│ Group ┆ Cost ┆ a   ┆ b    ┆ c    │
│ ---   ┆ ---  ┆ --- ┆ ---  ┆ ---  │
│ str   ┆ i32  ┆ i64 ┆ i64  ┆ i64  │
╞═══════╪══════╪═════╪══════╪══════╡
│ A     ┆ 1    ┆ 1   ┆ 2    ┆ 3    │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ B     ┆ 1    ┆ 1   ┆ 1    ┆ 1    │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ A     ┆ 1    ┆ 2   ┆ null ┆ null │

所以我需要类似.explode()的东西,但是列的东方。是否有可能有可能的funciton?

非常感谢

I have a function which returns a list type column. Hence, one of my columns is a list. I'd like to turn this list column into multiple columns. For example:

use polars::prelude::*;
use polars::df;

fn main() {
    let s0 = Series::new("a", &[1i64, 2, 3]);
    let s1 = Series::new("b", &[1i64, 1, 1]);
    let s2 = Series::new("c", &[Some(2i64), None, None]);
    // construct a new ListChunked for a slice of Series.
    let list = Series::new("foo", &[s0, s1, s2]);

    // construct a few more Series.
    let s0 = Series::new("Group", ["A", "B", "A"]);
    let s1 = Series::new("Cost", [1, 1, 1]);
    let df = DataFrame::new(vec![s0, s1, list]).unwrap();

    dbg!(df);

At this stage DF looks like this:

┌───────┬──────┬─────────────────┐
│ Group ┆ Cost ┆ foo             │
│ ---   ┆ ---  ┆ ---             │
│ str   ┆ i32  ┆ list [i64]      │
╞═══════╪══════╪═════════════════╡
│ A     ┆ 1    ┆ [1, 2, 3]       │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ B     ┆ 1    ┆ [1, 1, 1]       │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ A     ┆ 1    ┆ [2, null, null] │

Question From here, I'd like to get:

┌───────┬──────┬─────┬──────┬──────┐
│ Group ┆ Cost ┆ a   ┆ b    ┆ c    │
│ ---   ┆ ---  ┆ --- ┆ ---  ┆ ---  │
│ str   ┆ i32  ┆ i64 ┆ i64  ┆ i64  │
╞═══════╪══════╪═════╪══════╪══════╡
│ A     ┆ 1    ┆ 1   ┆ 2    ┆ 3    │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ B     ┆ 1    ┆ 1   ┆ 1    ┆ 1    │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ A     ┆ 1    ┆ 2   ┆ null ┆ null │

So I need something like .explode() but column-wise orient. Is there an existent funciton for this or a workaround potentially?

Many thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北方的巷 2025-02-11 03:08:44

是的,你可以。通过Polars Lazy,我们可以使用list()名称空间访问表达式API,以通过索引获取元素。

let out = df
    .lazy()
    .select([
        all().exclude(["foo"]),
        col("foo").list().get(0).alias("a"),
        col("foo").list().get(1).alias("b"),
        col("foo").list().get(2).alias("c"),
    ])
    .collect()?;
dbg!(out);
┌───────┬──────┬─────┬──────┬──────┐
│ Group ┆ Cost ┆ a   ┆ b    ┆ c    │
│ ---   ┆ ---  ┆ --- ┆ ---  ┆ ---  │
│ str   ┆ i32  ┆ i64 ┆ i64  ┆ i64  │
╞═══════╪══════╪═════╪══════╪══════╡
│ A     ┆ 1    ┆ 1   ┆ 2    ┆ 3    │
│ B     ┆ 1    ┆ 1   ┆ 1    ┆ 1    │
│ A     ┆ 1    ┆ 2   ┆ null ┆ null │
└───────┴──────┴─────┴──────┴──────┘

Yes you can. Via polars lazy, we get access the to the expression API and we can use the list() namespace, to get elements by index.

let out = df
    .lazy()
    .select([
        all().exclude(["foo"]),
        col("foo").list().get(0).alias("a"),
        col("foo").list().get(1).alias("b"),
        col("foo").list().get(2).alias("c"),
    ])
    .collect()?;
dbg!(out);
┌───────┬──────┬─────┬──────┬──────┐
│ Group ┆ Cost ┆ a   ┆ b    ┆ c    │
│ ---   ┆ ---  ┆ --- ┆ ---  ┆ ---  │
│ str   ┆ i32  ┆ i64 ┆ i64  ┆ i64  │
╞═══════╪══════╪═════╪══════╪══════╡
│ A     ┆ 1    ┆ 1   ┆ 2    ┆ 3    │
│ B     ┆ 1    ┆ 1   ┆ 1    ┆ 1    │
│ A     ┆ 1    ┆ 2   ┆ null ┆ null │
└───────┴──────┴─────┴──────┴──────┘

猫九 2025-02-11 03:08:44

该代码在V0.27.2中的Porars的Rust V1.67上进行了测试。

    let out = df
    .lazy()
    .with_columns([
        col("foo").arr().get(lit(0)).alias("a"),
        col("foo").arr().get(lit(1)).alias("b"),
        col("foo").arr().get(lit(2)).alias("c"),
    ])
    .drop_columns(["foo"])
    .collect()?;

    println!("out:\n{out}");

另一种使用循环的方式:

    let mut lazyframe = df.lazy();
    let column_name: Vec<char> = ('a'..='z').into_iter().collect();

    for (index, ch) in column_name.iter().enumerate().take(3) {
        lazyframe = lazyframe
        .with_columns([
            // split list into new columns
            col("foo").arr().get(lit(index as i64)).alias(&ch.to_string()),
        ])
    }

    let out = lazyframe
    .drop_columns(["foo"])
    .collect()?;

    println!("out:\n{out}");

This code was tested on Rust v1.67 for polars in v0.27.2.

    let out = df
    .lazy()
    .with_columns([
        col("foo").arr().get(lit(0)).alias("a"),
        col("foo").arr().get(lit(1)).alias("b"),
        col("foo").arr().get(lit(2)).alias("c"),
    ])
    .drop_columns(["foo"])
    .collect()?;

    println!("out:\n{out}");

Another way using for loop:

    let mut lazyframe = df.lazy();
    let column_name: Vec<char> = ('a'..='z').into_iter().collect();

    for (index, ch) in column_name.iter().enumerate().take(3) {
        lazyframe = lazyframe
        .with_columns([
            // split list into new columns
            col("foo").arr().get(lit(index as i64)).alias(&ch.to_string()),
        ])
    }

    let out = lazyframe
    .drop_columns(["foo"])
    .collect()?;

    println!("out:\n{out}");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文