问题
我想从mysql
数据库中读取数据到polars
数据框架中。我正在使用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
如何使用Vec<Country>
生成一个polars dataframe
来自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();
可能的解决方案
我能想到的唯一解决方案是,如果我可以为Country
结构体中的每一列/数据创建一个序列,并使用这些单独的序列创建一个数据框。
我不知道如何将Vec<Country>
分解成Vec<country>
和Vec<count>
。
Vec::with_capacity(v.len())
初始化空向量会更快。 - Jmb