如何将arrow_rs的FixedSizeList转换为Polars Series?
将Arrow RS的FixedSizeListArray转换为Polars Series
我通过第三方库获取了arrow_rs的FixedSizeListArray类型数据,需要将其转换为Polars的Series。以下是模拟第三方库输出的函数:
use arrow::array::FixedSizeListArray; use arrow::array::types::Int32Type; fn fixed_size_list_source()->FixedSizeListArray { let data = vec![ Some(vec![Some(0), Some(1), Some(2)]), None, Some(vec![Some(3), None, Some(5)]), Some(vec![Some(6), Some(7), Some(45)]), ]; FixedSizeListArray::from_iter_primitive::<Int32Type, _, _>(data, 3) }
我尝试使用Polars的from_arrow_rs方法,但无法生成它所需的&dyn arrow::array::Array输入参数。我试过以下代码:
let list_array = fixed_size_list_source(); let la= Box::new(list_array).into();
但出现报错:
the trait bound `&dyn arrow::array::Array: From<Box<arrow::array::FixedSizeListArray>>` is not satisfied required for `Box<arrow::array::FixedSizeListArray>` to implement `Into<&dyn arrow::array::Array>`
解决方案
问题出在错误的trait对象转换方式上,Box<FixedSizeListArray>无法直接通过into()转为&dyn Array。以下是两种可行的转换方案:
方案1:直接引用强转 trait 对象
直接将FixedSizeListArray的引用转换为&dyn Array,适配from_arrow_rs的参数要求:
use polars::prelude::*; fn main() { let list_array = fixed_size_list_source(); // 将FixedSizeListArray的引用直接转为&dyn Array trait对象 let series = Series::from_arrow_rs("fixed_list", &list_array as &dyn arrow::array::Array) .expect("转换Polars Series失败"); println!("{:?}", series); }
方案2:装箱后转为 trait 对象再解引用
先将FixedSizeListArray装箱为Box<dyn Array>,再解引用得到&dyn Array:
use polars::prelude::*; fn main() { let list_array = fixed_size_list_source(); // 装箱并转换为Box<dyn Array> trait对象 let boxed_array: Box<dyn arrow::array::Array> = Box::new(list_array); // 解引用得到&dyn Array let series = Series::from_arrow_rs("fixed_list", &*boxed_array) .expect("转换Polars Series失败"); println!("{:?}", series); }
两种方案都能正确将FixedSizeListArray转换为Polars Series,本质都是正确生成from_arrow_rs所需的&dyn arrow::array::Array trait对象。
内容的提问来源于stack exchange,提问作者Dean MacGregor
相关产品推荐
相关产品推荐

