Rust:使用结构向量的极坐标中的数据帧

Ham*_*air 3 sql dataframe rust rust-sqlx rust-polars

问题

我想将数据polarsmysql数据库读入数据帧。我在用sqlx

sqlx生成结构向量,例如:Vec<Country>如下:

来自sqlx 文档

// no traits are needed
struct Country { country: String, count: i64 }

let countries = sqlx::query_as!(Country,
        "
SELECT country, COUNT(*) as count
FROM users
GROUP BY country
WHERE organization = ?
        ",
        organization
    )
    .fetch_all(&pool) // -> Vec<Country>
    .await?;

// countries[0].country
// countries[0].count
Run Code Online (Sandbox Code Playgroud)

我如何使用它Vec<Country>来生成极坐标数据框

来自polars 文档


 use polars_core::prelude::*;
 let s0 = Series::new("a", &[1i64, 2, 3]);
 let s1 = Series::new("b", &[1i64, 1, 1]);
 let s2 = Series::new("c", &[2i64, 2, 2]);
 let list = Series::new("foo", &[s0, s1, s2]);

 let s0 = Series::new("B", [1, 2, 3]);
 let s1 = Series::new("C", [1, 1, 1]);
 let df = DataFrame::new(vec![list, s0, s1]).unwrap();
Run Code Online (Sandbox Code Playgroud)

可能的解决方案

我能想到的唯一解决方案是,如果我可以为结构内的每个列/数据创建一个系列Country,并使用这些单独的系列来创建一个数据框。

我不知道如何将 a 分解Vec<Country>Vec<country>Vec<count>

rit*_*e46 5

您可以使用构建器或从迭代器收集。从迭代器收集通常很快,但在这种情况下,它需要您循环Vec<Country>两次,因此您应该进行基准测试。

以下是所示两种解决方案的示例函数。

use polars::prelude::*;

struct Country {
    country: String,
    count: i64,
}

fn example_1(values: &[Country]) -> (Series, Series) {
    let ca_country: Utf8Chunked = values.iter().map(|v| &*v.country).collect();
    let ca_count: NoNull<Int64Chunked> = values.iter().map(|v| v.count).collect();
    let mut s_country: Series = ca_country.into();
    let mut s_count: Series = ca_count.into_inner().into();
    s_country.rename("country");
    s_count.rename("country");
    (s_count, s_country)
}

fn example_2(values: &[Country]) -> (Series, Series) {
    let mut country_builder = Utf8ChunkedBuilder::new("country", values.len(), values.len() * 5);
    let mut count_builder = PrimitiveChunkedBuilder::<Int64Type>::new("count", values.len());

    values.iter().for_each(|v| {
        country_builder.append_value(&v.country);
        count_builder.append_value(v.count)
    });

    (
        count_builder.finish().into(),
        country_builder.finish().into(),
    )
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,如果你想要最大的性能,我真的推荐connector-x。它集成了极坐标和箭头,并且具有疯狂的性能。