最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rust - How can i construct and concat a dataframe or series with Array elements? - Stack Overflow

programmeradmin5浏览0评论

Suppose I wanted to add into my dataframe a column for arrays. This can be done easily in the python implementation by specifying the schema at construction. Here is some code to show off my issue

fn main() {
  let ArrayType = DataType::Array(Box::new(DataType::Array(Box::new(DataType::Int64), 2), 2)
  let mut s1 = Series::new_empty("test".into(), &ArrayType);
  ...
  // I can't add data to this array
  let test_data = Array2::from_shape_vec((2,2), vec![1,2,3,4]).unwrap();
  // this can't be added directly, so I tried iterating over it and using list builders
  // but i must be doing something wrong
}

It seams like I need to use a chunked array builder, but I have not been able to find the correct syntax for doing this with arrays. I can construct a list of lists, but I want to take advantage of the enforced sizing from the array data type.

I have tried list primitive chunk builders

let mut builder = ListPrimitiveChunkedBuilder::new(name, capacity, values_capacity, inner_type);

But elements constructed this way cannot be pushed into a series with the array data type. The documentation is lacking on how to add lists or arrays into Series, Column, or DataFrames.

This post is incredibly unhelpful as the answer is "you just can't do this in rust". If this where the case then why does the official documentation suggest that this is something you should be able to do in rust. There are also no issues about why this has not yet been implemented.

Suppose I wanted to add into my dataframe a column for arrays. This can be done easily in the python implementation by specifying the schema at construction. Here is some code to show off my issue

fn main() {
  let ArrayType = DataType::Array(Box::new(DataType::Array(Box::new(DataType::Int64), 2), 2)
  let mut s1 = Series::new_empty("test".into(), &ArrayType);
  ...
  // I can't add data to this array
  let test_data = Array2::from_shape_vec((2,2), vec![1,2,3,4]).unwrap();
  // this can't be added directly, so I tried iterating over it and using list builders
  // but i must be doing something wrong
}

It seams like I need to use a chunked array builder, but I have not been able to find the correct syntax for doing this with arrays. I can construct a list of lists, but I want to take advantage of the enforced sizing from the array data type.

I have tried list primitive chunk builders

let mut builder = ListPrimitiveChunkedBuilder::new(name, capacity, values_capacity, inner_type);

But elements constructed this way cannot be pushed into a series with the array data type. The documentation is lacking on how to add lists or arrays into Series, Column, or DataFrames.

This post is incredibly unhelpful as the answer is "you just can't do this in rust". If this where the case then why does the official documentation suggest that this is something you should be able to do in rust. There are also no issues about why this has not yet been implemented.

Share Improve this question edited Jan 22 at 18:21 Harlan Heilman asked Jan 18 at 7:02 Harlan HeilmanHarlan Heilman 233 bronze badges 5
  • Box::new doesn't take 2 parameters, did you miss some parentheses? – cafce25 Commented Jan 18 at 10:10
  • What's Array2? – cafce25 Commented Jan 18 at 10:16
  • You should also probably know that the Rust crate is a byproduct of Python polars, it's "just a dump of the internals" according to a polars dev. That means not everything doable in Python necessarily has to be doable similarly in Rust and just because a documentation page exists doesn't mean it's directly supported in Rust either. – cafce25 Commented Jan 18 at 10:34
  • @cafce25 yes i missed parentheses when typing it in here. Array2 is a ndarray structure for a 2d array. Thank you for the input. It is a bit annoying that not everything is doable in rust. – Harlan Heilman Commented Jan 19 at 3:59
  • Please edit your question to fix the typos and add the missing information. I'd recommend typing out examples in your editor, make sure they produce the errors you claim and then copy and paste it to Stack Overflow, that way you minimize the chance for typos which only distract from the real problem. – cafce25 Commented Jan 19 at 8:44
Add a comment  | 

1 Answer 1

Reset to default 1

You can make Arrays (aka FixedSizeListArray) directly using the polars_arrow crate like this:

use polars_arrow::array::FixedSizeListArray;
use polars_arrow::datatypes::Field;
use polars_arrow::array::Float64Array;

fn main() {
    let values = Float64Array::from_slice([1.1,2.2,3.3,4.4]).boxed();
    let list = FixedSizeListArray::try_new(
        ArrowDataType::FixedSizeList(
            Box::new(Field::new("a".into(), ArrowDataType::Float64, false)), 
            2 //this 2 defines the width
        ),
        2, //this 2 defines how many rows
        values,
        None
    ).unwrap();
    let s = Series::from_arrow("array".into(), Box::new(list)).unwrap();
    eprintln!("{}",s);
    
}

resulting in

Series: 'array' [array[f64, 2]]
[
        [1.1, 2.2]
        [3.3, 4.4]
]

Note that the original data is fed with a single slice which must be the same length as the width * the number of rows.

There's also a MutabeFixedSizeList that works more like a Builder.

If you want to add to that Series you have to make a new Series and then add to it with s.append(&s2) but then you also need to make it mutable.

Check the tests for more examples of using the FixedSizeListArray.

Alternatively

You can make your Series as a primitive array and then use reshape_array on it to turn it into an Array. That looks like this:

fn main() {
    let s = ChunkedArray::<Float64Type>::from_vec(
        "array".into(), 
        vec![1.1, 2.2, 3.3, 4.4]
        )
        .into_series()
        .reshape_array(&[
            ReshapeDimension::Infer, // this is how many rows
            ReshapeDimension::Specified(Dimension::new(2)), // this is width
        ])
        .unwrap();

    eprintln!("{}", s);
}
shape: (2,)
Series: 'array' [array[f64, 2]]
[
        [1.1, 2.2]
        [3.3, 4.4]
]

Another alternative

    let df = DataFrame::new(vec![
        Series::from_any_values_and_dtype(
            "bit_flags".into(),
            &[
                vec![true, true, true, true, false],
                vec![false, true, true, true, true],
            ]
            .iter()
            .map(|item| AnyValue::List(Series::new("".into(), item)))
            .collect::<Vec<AnyValue>>(),
            &DataType::Array(Box::new(DataType::Boolean), 5),
            true,
        )?
        .into()
    ])?
发布评论

评论列表(0)

  1. 暂无评论