如何转换 Vec<ndarray::Array1> 的集合成一个Array2? [英] How to convert a collection of Vec<ndarray::Array1> into an Array2?
问题描述
我正在尝试使用 ndarray crate 从一维数组的 Vec
创建一个二维数组.在当前的实现中,我将 Vec
作为一维数组的集合,我很难弄清楚如何将其转换为 Array2
Vec
上尝试了 from_vec()
但它产生了 Array1
.我想过使用 stack!
宏,但我不确定如何在上面的 Vec
上调用它.我使用的是 ndarray 0.12.1 和 Rust 1.31.0.
I'm trying to create a 2D array from a Vec
of 1D arrays using the ndarray crate. In the current implementation, I have Vec<Array1<u32>>
as the collection of 1D arrays, and I'm having a hard time figuring out how to convert it to Array2<u32>
. I've tried from_vec()
on Vec<Array1<u32>>
but it yielded Array1<Array1<u32>>
. I thought of using the stack!
macro, but I'm not sure how to call it on the above Vec
. I'm using ndarray 0.12.1 and Rust 1.31.0.
推荐答案
我对 ndarray
不是很熟悉,但看起来你必须将数据展平作为中间步骤然后重建从那.迭代器可能会更有效,但我没有看到从迭代器构建的方法也可以让您指定形状.
I'm not hugely familiar with ndarray
, but it looks like you have to flatten the data as an intermediate step and then rebuild from that. An iterator would probably have been more efficient but I don't see a method to build from an iterator that also lets you specify a shape.
这可能不是最性能的方法,但它至少有效:
It likely isn't the most performant way to to this, but it does at least work:
fn to_array2<T: Copy>(source: &[Array1<T>]) -> Result<Array2<T>, impl std::error::Error> {
let width = source.len();
let flattened: Array1<T> = source.into_iter().flat_map(|row| row.to_vec()).collect();
let height = flattened.len() / width;
flattened.into_shape((width, height))
}
请注意,如果源数组的长度不同,它可能会失败.该解决方案不是 100% 稳健的,因为如果一个阵列较小但由另一个更长的阵列补偿,它不会失败.可能值得在那里添加一个检查来防止这种情况发生,但我会把它留给你.
Note that it can fail if the source arrays has different lengths. This solution is not 100% robust because it won't fail if one array is smaller but compensated by another array being longer. It is probably worth adding a check in there to prevent that, but I'll leave that to you.
这篇关于如何转换 Vec<ndarray::Array1> 的集合成一个Array2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!