如何将sqlx从MySQL查询得到的Vec<Struct>转换为polars的DataFrame
你可以通过Rust迭代器的unzip方法一次遍历完成字段拆分,完整实现代码如下:
use polars_core::prelude::*; use sqlx::MySqlPool; // 你已定义的Country结构体 struct Country { country: String, count: i64 } // 完整的查询+转换逻辑示例 async fn query_countries_and_convert_to_df(organization: &str, pool: &MySqlPool) -> Result<DataFrame, Box<dyn std::error::Error>> { // 从MySQL查询拿到Vec<Country> let countries = sqlx::query_as!(Country, r#" SELECT country, COUNT(*) as count FROM users WHERE organization = ? GROUP BY country "#, organization ) .fetch_all(pool) .await?; // 单次遍历拆分两个字段为独立向量 let (country_list, count_list): (Vec<String>, Vec<i64>) = countries .into_iter() .map(|item| (item.country, item.count)) .unzip(); // 构造Series再生成DataFrame let df = DataFrame::new(vec![ Series::new("country", country_list), Series::new("count", count_list) ])?; Ok(df) }
注意事项
- 上述代码用
into_iter会消费掉原Vec<Country>,如果你后续还需要使用这个集合,可以把into_iter替换为iter,同时将map逻辑改为.map(|item| (item.country.clone(), item.count)),克隆String类型的country字段来生成新的向量 unzip方法可以直接把迭代器返回的二元组自动拆分到两个独立的Vec中,相比两次遍历分别提取字段性能更好- 如果你的结构体字段较多,可以自行扩展map返回的元组长度,配合对应类型标注即可一次性拆分出所有字段的向量
内容的提问来源于stack exchange,提问作者Hamza Zubair
相关产品推荐
相关产品推荐

