是否可以从ndarray获取非连续的切片?

man*_*ndy 4 indexing matrix rust

是否可以ndarray使用Vec而不是Slice对象来索引Rust 矩阵中的列?我能找到的唯一文档适用于使用连续列进行切片

具体来说,我试图在Python中实现类似下面的代码:

x = np.array([[1,2,3,4,5,6], [7,8,9,10,11,12]])
idx = [0,1,2,4]
x[:, idx]
Run Code Online (Sandbox Code Playgroud)

结果x[:, idx]将是包含所有行的矩阵的子集,并且仅包含所描述的列idx,即[0,1,2,4].

我目前正在使用ndarray(如标题所示),但我无法找到一种在非连续切片上进行子集化的方法.举例来说,你可以传递ndarray,可以取Slice一个start,stop和index,但我不能找到一种方式来传递,可以不使用描述列的列表Slice对象.

例如:

#[macro_use]
extern crate ndarray;

fn main() {
    let mut x = array![[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]];
    let idx = vec![0, 1, 2, 4];
    // The following works as expected
    let y = x.slice(s![.., 0..2]);
    println!("{:?}", y);
    // This is conceptually what I would like to do but
    // It does not work.
    let y = x.slice(s![.., idx]);
}
Run Code Online (Sandbox Code Playgroud)

Sve*_*ach 6

Numpy中"高级索引"的类似ArrayBase::select()方法是:

use ndarray::{array, Axis};

fn main() {
    let x = array![[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]];
    let idx = vec![0, 1, 2, 4];
    println!("{}", x.select(Axis(1), &idx));
}
Run Code Online (Sandbox Code Playgroud)

产生输出

[[1, 2, 3, 5],
 [7, 8, 9, 11]]
Run Code Online (Sandbox Code Playgroud)

请注意,生成的数组是所选元素的副本(就像它在Numpy中一样).根据您的使用情况,您可能不需要副本; 你可以通过迭代idx和使用x.slice(s![.., i])全部i来完成idx.