rustrust-polars

How can i construct and concat a dataframe or series with Array elements?


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.


Solution

  • 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()
        ])?