1

I am using the numpy crate in Rust to work with 2D arrays that come from python. PyArray (https://docs.rs/numpy/0.11.0/numpy/array/struct.PyArray.html) implements a from_vec2() function, which converts a Vec<Vec<T>> into a PyArray<T, 2> (2D PyArray), and a to_vec() function, which flattens the 2D array into a 1D vector and returns Vec<T>, but it does not implement to_vec2(). Is there a simple way to do this conversion which I am missing, or would I have to implement this function by hand?

Thanks.

Yaxlat
  • 665
  • 1
  • 10
  • 25

1 Answers1

1

You can use .iter along with some iterator methods to do this:

arr.iter().unwrap().map(|arr| arr.to_vec().unwrap()).collect::<Vec<_>>()
Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • Unfortunately .iter() forces conversion into a vector first, and so you are once again left with the 2D array flattened into a 1D array, thus the elements that you are mapping over are not themselves arrays. – Yaxlat Jan 03 '21 at 17:02
  • @Yaxlat There's an `iter` defined for `PyArray`s, and you map `to_vec` on each element two get a 2d vector. – Aplet123 Jan 03 '21 at 17:05
  • I did try this, but ```iter``` flattens the ```PyArray``` so the elements are just going to floats or integers or whatever, rather than arrays that you could apply ```to_vec``` to. Your code just gives an error which says that type f64 does not have a method called ```to_vec```. I've just implemented this manually for now but it is pretty messy. Thanks for the help anyway! – Yaxlat Jan 04 '21 at 15:22